package com.sqfw.project.wp.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.util.DateUtils;
import com.github.pagehelper.PageInfo;
import com.sqfw.common.constant.HttpStatus;
import com.sqfw.common.exception.base.BaseException;
import com.sqfw.common.utils.Query;
import com.sqfw.common.utils.SecurityUtils;
import com.sqfw.common.utils.StringUtils;
import com.sqfw.framework.web.domain.AjaxResult;
import com.sqfw.framework.web.page.TableDataInfo;
import com.sqfw.project.community.domain.*;
import com.sqfw.project.system.domain.SysDept;
import com.sqfw.project.system.domain.SysDictData;
import com.sqfw.project.system.domain.SysRole;
import com.sqfw.project.system.domain.SysUser;
import com.sqfw.project.system.mapper.SysDeptMapper;
import com.sqfw.project.system.mapper.SysDictDataMapper;
import com.sqfw.project.system.mapper.SysUserMapper;
import com.sqfw.project.utils.UpperItemUtils;
import com.sqfw.project.wp.domain.*;
import com.sqfw.project.wp.domain.vo.*;
import com.sqfw.project.wp.mapper.*;
import com.sqfw.project.wp.service.RedisService;
import com.sqfw.project.wp.service.TSMSSendLogService;
import com.sqfw.project.wp.service.TSmsUserService;
import com.sqfw.project.wpReport.domain.WpHoliday;
import com.sqfw.project.wpReport.mapper.WpHolidayMapper;
import com.sqfw.project.wpReport.service.IWpInfoDeptService;
import com.sqfw.project.zj.domain.ZjRecord;
import com.sqfw.project.zj.domain.ZjSoundCase;
import com.sqfw.project.zj.mapper.ZjRecordMapper;
import com.sqfw.project.zj.mapper.ZjSoundCaseMapper;
import com.sqfw.project.zj.service.IZjSoundCaseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sqfw.project.wp.service.IWpInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 工单表Service业务层处理
 *
 * @author lx
 * @date 2023-06-07
 */
@Slf4j
@Service
public class WpInfoServiceImpl implements IWpInfoService {

    @Autowired
    private WpInfoMapper wpInfoMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SysMiniFileMapper sysMiniFileMapper;

    @Autowired
    private WpHandleLogMapper wpHandleLogMapper;

    @Autowired
    private SysCodeMapper sysCodeMapper;

    @Autowired
    private WpVisitInfoMapper wpVisitInfoMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private WpHurryLogMapper wpHurryLogMapper;

    @Autowired
    private WpUpdateLogMapper wpUpdateLogMapper;

    @Autowired
    private WpBackInfoMapper wpBackInfoMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private TSMSSendLogService tsmsSendLogService;

    @Autowired
    private IWpInfoDeptService wpInfoDeptService;

    @Autowired
    private IZjSoundCaseService zjSoundCaseService;

    @Autowired
    private WpHolidayMapper wpHolidayMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;


    @Autowired
    private ZjRecordMapper zjRecordMapper;

    @Autowired
    private ZjSoundCaseMapper zjSoundCaseMapper;

    @Autowired
    private TSmsUserService tSmsUserService;

    @Autowired
    private WpEvaluateSatisMapper wpEvaluateSatisMapper;


    //有效期应该是每天, 不是24小时, redis原子自增, key不存在从0开始
    public static final Long EXPIRE = 60 * 60 * 24 * 1L;

    public static final int EXPTIME = 15;

    private static final Integer dayFive = 5;

    private static final Integer daySeven = 7;

    private static final Integer dayTen = 10;

    private static final Long ddRoleId = 182L;

    /**
     * 处理按钮点击前检查操作
     *
     * @param scid     工单主键
     * @param userName 用户
     * @param onOff    (0关闭窗口，1打开窗口)
     */
    public Boolean processHandle(String scid, String userName, int onOff) throws Exception {

        boolean flag = false;
        WpInfo wpInfo = wpInfoMapper.selectWpInfoByScid(scid);
        if (null == wpInfo) {
            throw new BaseException("工单不存在");
        }

        // 如果是关闭窗口操作则清空当前处理人
        if (0 == onOff) {
            flag = true;
            wpInfo.setCurrWorker(null);
            wpInfo.setCurrWorkTime(null);
            wpInfoMapper.updateWpInfoCurrWork(wpInfo);
            return flag;
        }

        long currTime = System.currentTimeMillis();

        // 如果无人处理保存当前处理人结束
        if (StringUtils.isEmpty(wpInfo.getCurrWorker()) || StringUtils.isNull(wpInfo.getCurrWorkTime())) {
            flag = true;
            wpInfo.setCurrWorker(userName);
            wpInfo.setCurrWorkTime(currTime);
            wpInfoMapper.updateWpInfoCurrWork(wpInfo);
            return flag;
        }

        // 如果超过15分钟 当前处理人和时间
        long overTimeMin = (currTime - wpInfo.getCurrWorkTime()) / 1000L / 60L;
        boolean isOvertime = overTimeMin > EXPTIME;
        if (isOvertime) {
            flag = true;
            wpInfo.setCurrWorker(userName);
            wpInfo.setCurrWorkTime(currTime);
            wpInfoMapper.updateWpInfoCurrWork(wpInfo);
            return flag;
        }

        // 如果是本人打开窗口重置处理时间
        if (StringUtils.equals(userName, wpInfo.getCurrWorker())) {
            flag = true;
            wpInfo.setCurrWorker(userName);
            wpInfo.setCurrWorkTime(currTime);
            wpInfoMapper.updateWpInfoCurrWork(wpInfo);
            return flag;
        }

        return flag;
    }

    /**
     * 查询工单表详情
     *
     * @param scid 工单表主键
     * @return 工单表
     */
    @Override
    public WpInfo selectWpInfoByScid(String scid) {

        WpInfo wpInfo = wpInfoMapper.selectWpInfoByScid(scid);

        if (wpInfo == null) {
            throw new BaseException("未查询到工单");
        }
        ZjSoundCase zjSoundCase = zjSoundCaseMapper.selectZjSoundCaseByWpid(wpInfo.getWpid());
        if (zjSoundCase != null) {
            wpInfo.setSubmitReason(zjSoundCase.getSubmitReason());
        }
        if (StringUtils.isNotEmpty(wpInfo.getCause())) {
            String cause = wpInfo.getCause();
            List<String> causeList = new ArrayList<>(Arrays.asList(cause.split(",")));
            wpInfo.setCauseList(causeList);
        }
        //工单标签
        if (StringUtils.isNotEmpty(wpInfo.getDictData())) {
            String[] split = wpInfo.getDictData().split(",");
            Long[] longs = new Long[split.length];

            for (int i = 0; i < split.length; i++) {
                longs[i] = Long.parseLong(split[i]);
            }
            List<Long> dictDataAll = new ArrayList<>();
            Collections.addAll(dictDataAll, longs);
            wpInfo.setDictDataAll(dictDataAll);
        }
        String fileno = wpInfo.getFileno();
        if (fileno != null) {
            String[] split = wpInfo.getFileno().split(",");
            if (split.length > 0) {
                List<SysMiniFile> sysMiniFiles = sysMiniFileMapper.selectSysMiniFileByIds(split);
                wpInfo.setSysMiniFiles(sysMiniFiles);
            }
        }
        WpHandleLog wpHandleLog = new WpHandleLog();
        wpHandleLog.setWpid(wpInfo.getWpid());
        List<WpHandleLog> wpHandleLogs = wpHandleLogMapper.selectWpHandleLogList(wpHandleLog);
        //TODO  后期优化
        if (!wpHandleLogs.isEmpty()) {

            //只有承办单位处理的时候会多出这几个字段
            WpHandleLog logCon = wpHandleLogs.stream()
                    .filter(log -> "承办单位处理".equals(log.getLastState()))
                    .max(Comparator.comparing(WpHandleLog::getUpdateTime)).orElse(null);
            if (logCon != null) {
                //工单轨迹特有字段
                wpInfo.setSatisfied(logCon.getSatisfied());
                wpInfo.setReasonable(logCon.getReasonable());
                wpInfo.setSolved(logCon.getSolved());
            }

            //退单展示退单原因   督导退回坐席
            WpHandleLog logCon1 = wpHandleLogs.stream()
                    .filter(logHan -> "坐席处理".equals(logHan.getNextState()) &&
                            ("督导处理".equals(logHan.getLastState())
                                    || "培训助理处理".equals(logHan.getLastState())
                                    || "质检审核处理".equals(logHan.getLastState())))
                    .max(Comparator.comparing(WpHandleLog::getUpdateTime)).orElse(null);
            if (logCon1 != null) {
                wpInfo.setBackClass(logCon1.getBackClass());
            }
            // 循环查询工单轨迹
            for (WpHandleLog handleLog : wpHandleLogs) {
                if (StringUtils.isNotEmpty(handleLog.getOperator())) {
                    SysUser user = userMapper.selectUserByCode(handleLog.getOperator());
                    if (user != null) {
                        handleLog.setNickName(user.getNickName());
                    }
                }
                if (StringUtils.isNotEmpty(handleLog.getDepartment())) {
                    SysDept sysDept = sysDeptMapper.selectDeptById(Long.valueOf(handleLog.getDepartment()));
                    if (sysDept != null) {
                        handleLog.setDepartmentName(sysDept.getDeptName());
                    }
                }
            }
            wpInfo.setWpHandleLogs(wpHandleLogs);
        }
        //处理工单回访过的工单，需要展示回访满意度字段
        if ("工单回访".equals(wpInfo.getState())) {
            WpVisitInfo wpVisitInfo = wpVisitInfoMapper.selectWpVisitInfoByWpid(wpInfo.getWpid());
            if (wpVisitInfo != null) {
                wpInfo.setAcceptVisit(wpVisitInfo.getAcceptVisit());
                wpInfo.setIsanswer(wpVisitInfo.getIsanswer());
                wpInfo.setIssatisfied(wpVisitInfo.getIssatisfied());
                wpInfo.setIsReply(wpVisitInfo.getIsReply());
                wpInfo.setIssatisfiedReason(wpVisitInfo.getIssatisfiedReason());
                wpInfo.setIssatisfiedOther(wpVisitInfo.getIssatisfiedOther());
            }
        }

        return wpInfo;
    }

    /**
     * 查询工单表列表
     *
     * @param wpInfo 工单表
     * @return 工单表
     */
    @Override
    public List<WpInfo> selectWpInfoList(WpInfo wpInfo) throws ParseException {


        List<String> districtAll = wpInfo.getDistrictAll();
        if (StringUtils.isNotEmpty(districtAll)) {
            for (int i = 0; i < districtAll.size(); i++) {
                if (i == 0) {
                    //区域
                    wpInfo.setDistrict(districtAll.get(i));
                }
                if (i == 1) {
                    //街道
                    wpInfo.setStreet(districtAll.get(i));
                }
                if (i == 2) {
                    //居委会
                    wpInfo.setCommittee(districtAll.get(i));

                }
            }
        }
        //内容分类查询条件
        List<List<String>> classAllFind = wpInfo.getClassAllFind();

        //内容分类查询
        if (StringUtils.isEmpty(classAllFind)) {
            wpInfo.setClassAll(null);
        } else {
            List<String> classAllCon = new ArrayList<>();
            for (List<String> strings : classAllFind) {
                classAllCon.add(strings.get(strings.size() - 1));
            }
            wpInfo.setClassAll(classAllCon);
        }
        //排序相关
        String order = wpInfo.getOrder();
        String prop = wpInfo.getProp();
        if ("dictDataList".equals(prop)) {
            prop = "dictData";
        }
        if ("initiatorName".equals(prop)) {
            prop = "sender";
        }
        if ("mainUnitName".equals(prop)) {
            prop = "mainUnit";
        }

        String orderBy = UpperItemUtils.upperName(order, prop);

        wpInfo.setOrderBy(orderBy);

        List<WpInfo> wpInfos = wpInfoMapper.selectWpInfoList(wpInfo);
        // 根据工号查询用户姓名
        Set<String> codeSet = new HashSet<>(wpInfos.size() + 6);
        wpInfos.stream().forEach(w -> {
            if (StringUtils.isNotEmpty(w.getCode())) {
                codeSet.add(w.getCode());
            }
        });
        List<SysUser> codeUsetList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(codeSet)) {
            List<String> codeList = new ArrayList<>();
            codeList.addAll(codeSet);
            codeUsetList = userMapper.getUserByCodes(codeList);
        }
        for (WpInfo info : wpInfos) {
            if (!StringUtils.isEmpty(info.getPhoneno())) {
                String phoneno = info.getPhoneno();
                Integer countSize = wpInfoMapper.countWpInfoByPhoneno(phoneno);
                info.setPhoneCalls(countSize);
            }
            //暂存列表展示一共来电多少次
            if ("暂存".equals(info.getMemoryInfo())) {
                info.setSellFlag(false);
                SysUser user = SecurityUtils.getLoginUser().getUser();
                List<Long> roleIds = user.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList());

                Boolean sellFlag = getSellFlag(roleIds);
                if (sellFlag) {
                    info.setSellFlag(true);
                }
                if (!StringUtils.isEmpty(info.getCode()) && info.getCode().equals(user.getCode())) {
                    info.setSellFlag(true);
                }

                //工单标签
                if (StringUtils.isNotEmpty(info.getDictData())) {
                    String[] split = info.getDictData().split(",");
                    Long[] longs = new Long[split.length];

                    List<String> dictDataList = new ArrayList<>();
                    for (int i = 0; i < split.length; i++) {
                        longs[i] = Long.parseLong(split[i]);
                        SysDictData sysDictData = dictDataMapper.selectDictDataById(longs[i]);
                        if (sysDictData != null) {
                            dictDataList.add(sysDictData.getDictLabel());
                        }
                    }
                    info.setDictDataList(dictDataList);
                }

            }

            if (StringUtils.isNotEmpty(info.getDeptLevel2())) {
                SysDept sysDept = sysDeptMapper.selectDeptById(Long.valueOf(info.getDeptLevel2()));
                if (sysDept != null) {
                    info.setMainUnitName(sysDept.getDeptName());
                }

            }
            //工单是否在处理中 true为处理中
            info.setProcessing(false);
            if (info.getCurrWorkTime() != null) {
                long currTime = System.currentTimeMillis();
                // 如果超过15分钟 当前处理人和时间
                long overTimeMin = (currTime - info.getCurrWorkTime()) / 1000L / 60L;
                boolean isOvertime = overTimeMin > EXPTIME;
                if (!isOvertime) {
                    info.setProcessing(true);
                }

            }
            String class1 = info.getClass1();
            String class2 = info.getClass2();
            String class3 = info.getClass3();
            String class4 = info.getClass4();

            StringBuffer name = new StringBuffer();

            if (StringUtils.isNotEmpty(class1)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class1));
                if (sysCode != null) {
                    info.setMainNodename(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(class2)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class2));
                if (sysCode != null) {
                    name.append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(class3)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class3));
                if (sysCode != null) {
                    name.append("/").append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(class4)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class4));
                if (sysCode != null) {
                    name.append("/").append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(name)) {
                info.setChildNodeName(name.toString());
            }

            String cbdwComplete = info.getCbdwComplete();
            if (StringUtils.isNotEmpty(cbdwComplete)) {
                //已完成
                if (cbdwComplete.equals("1")) {
                    info.setResidue("已完成");
                } else if (cbdwComplete.equals("0")) {
                    // 老数据的处理方式--2025-09-10
                    if ("工单归档".equals(info.getNextState())) {
                        info.setResidue("已完成");
                    }else {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String timeBoundry = info.getTimeBoundry();
                        if (StringUtils.isNotEmpty(timeBoundry)) {
                            String residueDay = checkResidueDay(simpleDateFormat.parse(timeBoundry));
                            info.setResidue(residueDay);
                        }
                    }
                }
            }
            // 根据工号查询用户姓名
            if (StringUtils.isNotEmpty(info.getCode())) {
                if (!CollectionUtils.isEmpty(codeUsetList)) {
                    for (SysUser codeUser : codeUsetList) {
                        if (info.getCode().equals(codeUser.getCode())) {
                            info.setInitiatorName(codeUser.getNickName());
                            break;
                        }
                    }
                }
            }

        }

        return wpInfos;
    }

    public Boolean getSellFlag(List<Long> roleIds) {
        boolean flag = false;
        if (roleIds.contains(120L)) {
            flag = true;
        }
        if (roleIds.contains(181L)) {
            flag = true;
        }
        if (roleIds.contains(200L)) {
            flag = true;
        }
        if (roleIds.contains(220L)) {
            flag = true;
        }
        if (roleIds.contains(223L)) {
            flag = true;
        }
        if (roleIds.contains(246L)) {
            flag = true;
        }
        if (roleIds.contains(247L)) {
            flag = true;
        }
        if (roleIds.contains(248L)) {
            flag = true;
        }
        if (roleIds.contains(249L)) {
            flag = true;
        }
        if (roleIds.contains(182L)) {
            flag = true;
        }
        if (roleIds.contains(266L)) {
            flag = true;
        }
        return flag;
    }


    /**
     * 新增工单表
     *
     * @param wpInfo 工单表
     * @return 结果
     */
    @Override
    public int insertWpInfo(WpInfo wpInfo) {

        //添加工单时间
        Date date = new Date();
        wpInfo.setStarttime(date);
        wpInfo.setUpdatetime(date);
        wpInfo.setCalltime(date);
        wpInfo.setRelName(wpInfo.getCustomerName());
        wpInfo.setRelAddress(wpInfo.getAddress());
        wpInfo.setRelPhoneno(wpInfo.getPhoneno());
        wpInfo.setRelCommittee(wpInfo.getCommittee());
        wpInfo.setRelDistrict(wpInfo.getDistrict());
        wpInfo.setRelStreet(wpInfo.getStreet());
        //处理时限，则默认10天
        wpInfo.setTimelimite(10);
        if (StringUtils.isNotEmpty(wpInfo.getDictDataAll())) {
            String join = StringUtils.join(wpInfo.getDictDataAll(), ",");
            wpInfo.setDictData(join);
        }

        String mainUnit = wpInfo.getMainUnit();
        //主办部门
        if (mainUnit != null) {
            String[] split = mainUnit.split(",");
            wpInfo.setDeptLevel2(split[split.length - 1]);
        }
        //协办部门1
        String assistUnit1 = wpInfo.getAssistUnit1();
        if (assistUnit1 != null) {
            String[] assistUnit1Split = assistUnit1.split(",");
            wpInfo.setDeptLevel2vice1(assistUnit1Split[assistUnit1Split.length - 1]);
        }
        //协办部门2
        String assistUnit2 = wpInfo.getAssistUnit2();
        if (assistUnit2 != null) {
            String[] assistUnit2Split = assistUnit2.split(",");
            wpInfo.setDeptLevel2vice2(assistUnit2Split[assistUnit2Split.length - 1]);
        }
        //判断是不是五大模块
        if (StringUtils.isNotEmpty(wpInfo.getClass2())) {
            //五大模块相关
            SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(wpInfo.getClass2()));
            if (StringUtils.isNotEmpty(sysCode.getFiveMajorModules())) {
                wpInfo.setFiveMajorModules(sysCode.getFiveMajorModules());
            }
        }
        if (StringUtils.isNotEmpty(wpInfo.getClass3())) {
            //五大模块相关
            SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(wpInfo.getClass3()));
            if (StringUtils.isNotEmpty(sysCode.getFiveMajorModules())) {
                wpInfo.setFiveMajorModules(sysCode.getFiveMajorModules());
            }
        }
        //添加完成后，需要将在主轨迹表添加轨迹数据
        this.insertWpHandleLog(wpInfo);
        if ("是".equals(wpInfo.getIsSoundCases())) {
            // 添加声音案例
            addSoundCase(wpInfo);
        }
        WpEvaluateSatis wpEvaluateSatis = wpEvaluateSatisMapper.getByWpid(wpInfo.getWpid());
        if (wpEvaluateSatis != null) {
            wpInfo.setEvaluateSatis(wpEvaluateSatis.getEvaluateSatis());
        }
        String scid = wpInfoMapper.selectWpInfoSeqScid();
        wpInfo.setScid("SQ" + scid);
        return wpInfoMapper.insertWpInfo(wpInfo);
    }

    //新增轨迹表数据
    @Transactional
    public void insertWpHandleLog(WpInfo wpInfo) {
        Date date = new Date();
        //添加完成后，需要将在主轨迹表添加轨迹数据
        WpHandleLog wpHandleLog = new WpHandleLog();
        //登录人员信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        wpHandleLog.setWpid(wpInfo.getWpid());
        wpHandleLog.setOperator(user.getCode());
        wpHandleLog.setMessage(wpInfo.getLastmessage());
        wpHandleLog.setLastState(wpInfo.getState());
        wpHandleLog.setNextState(wpInfo.getNextState());
        wpHandleLog.setSummary(wpInfo.getSummary());
        //部门id
        wpHandleLog.setDepartment(user.getDeptId().toString());

        //特有字段（承办单位处理,工单回访）
        wpHandleLog.setSatisfied(wpInfo.getSatisfied());
        wpHandleLog.setReasonable(wpInfo.getReasonable());
        wpHandleLog.setSolved(wpInfo.getSolved());
        wpHandleLog.setBackClass(wpInfo.getBackClass());
        wpHandleLog.setUpdateTime(date);
        if ("督导处理".equals(wpHandleLog.getNextState()) || "承办单位处理".equals(wpHandleLog.getNextState())) {
            //主办部门id
            wpHandleLog.setNextDepartment1(wpInfo.getDeptLevel2());
            //协助部门id
            wpHandleLog.setDeptLevel2vice1(wpInfo.getDeptLevel2vice1());
            wpHandleLog.setDeptLevel2vice2(wpInfo.getDeptLevel2vice2());
        }
        //代表承办单位到回访操作
        if ("工单回访".equals(wpHandleLog.getNextState()) && (!"质检审核处理".equals(wpHandleLog.getLastState()))) {
            //工单回访，需要向hfState中插入数据（1:5天内完成，2:10天内完成，3：超时完成）
            WpHandleLog log = new WpHandleLog();
            log.setWpid(wpInfo.getWpid());
            log.setNextState("承办单位处理");
            List<WpHandleLog> handleLogList = wpHandleLogMapper.selectWpHandleLogList(log);
            if (!CollectionUtils.isEmpty(handleLogList)) {
                WpHandleLog logCon = wpHandleLogMapper.selectWpHandleLogList(log).stream()
                        .max(Comparator.comparing(WpHandleLog::getUpdateTime))
                        .orElse(null);
                // 取第一次派单时间
                WpHandleLog logMin = wpHandleLogMapper.selectWpHandleLogList(log).stream()
                        .min(Comparator.comparing(WpHandleLog::getUpdateTime))
                        .orElse(null);
                if (logCon != null && logMin != null) {
                    //这一块是判断工作日相关
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    long year = calendar.get(Calendar.YEAR);
                    WpHoliday wpHoliday = new WpHoliday();
                    wpHoliday.setYearid(year);
                    List<WpHoliday> wpHolidays = wpHolidayMapper.selectWpHolidayList(wpHoliday);

                    List<String> dates = wpHolidays.stream()
                            .map(WpHoliday::getDtime)
                            .map(simpleDateFormat::format)
                            .collect(Collectors.toList());

                    Date timeFive = wpInfoDeptService.checkOntime(logMin.getUpdateTime(), dayFive, dates);

                    if (date.compareTo(timeFive) <= 0) {
                        //代表5天内完成
                        logCon.setHfState("1");

                    } else {
                        Date timeTen = wpInfoDeptService.checkOntime(logMin.getUpdateTime(), dayTen, dates);
                        try {
                            if (date.compareTo(timeTen) <= 0) {
                                //代表10天内完成
                                logCon.setHfState("2");
                            } else {
                                //代表超时完成
                                logCon.setHfState("3");
                            }

                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            if (StringUtils.isNotEmpty(wpInfo.getTimeBoundry())){
                                Date parse = dateFormat.parse(wpInfo.getTimeBoundry());
                                //如果是延期，且五天内没有完成
                                if (date.compareTo(parse)<=0){
                                    //代表10天内完成
                                    logCon.setHfState("2");
                                }
                            }

                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                    //todo 增加更新之前所有的轨迹
                    //更新之前所有历史轨迹的HfState字段值，避免在统计报表中统计条件hf_state为null的数据出现偏差不一致
                    if(StringUtils.isNotEmpty(logCon.getHfState())){
                        wpHandleLogMapper.updateAllHistoryHfSate(logCon);
                    }
                    wpHandleLogMapper.updateWpHandleLog(logCon);
                }
            }
        }
        String processId = wpHandleLogMapper.getWpHandleLogId();
        wpHandleLog.setProcessId("SQ" + processId);
        wpHandleLogMapper.insertWpHandleLog(wpHandleLog);
    }

    /**
     * 修改工单表
     *
     * @param wpInfo 工单表
     * @return 结果
     */
    @Transactional
    @Override
    public AjaxResult updateWpInfo(WpInfo wpInfo) {

            if (("质检审核处理".equals(wpInfo.getState())||"督导处理".equals(wpInfo.getState()))&&"坐席处理".equals(wpInfo.getNextState())){
                WpInfo infoCon = new WpInfo();
                infoCon.setDeptLevel2(null);
                infoCon.setMainUnit(null);
                infoCon.setAssistUnit1(null);
                infoCon.setAssistUnit2(null);
                infoCon.setDeptLevel2vice2(null);
                infoCon.setDeptLevel2vice1(null);
                infoCon.setScid(wpInfo.getScid());
                infoCon.setEndState(null);
                int i = wpInfoMapper.updateMainDeptByScid(infoCon);


                wpInfo.setDeptLevel2(null);
                wpInfo.setMainUnit(null);
                wpInfo.setAssistUnit1(null);
                wpInfo.setAssistUnit2(null);
                wpInfo.setDeptLevel2vice2(null);
                wpInfo.setDeptLevel2vice1(null);
                wpInfo.setEndState(null);

            }

            if ("工单暂存".equals(wpInfo.getState())||"坐席处理".equals(wpInfo.getState())){
                if ("质检审核处理".equals(wpInfo.getNextState())){
                    WpInfo infoCon = new WpInfo();
                    infoCon.setDeptLevel2(null);
                    infoCon.setMainUnit(null);
                    infoCon.setAssistUnit1(null);
                    infoCon.setDeptLevel2vice1(null);
                    infoCon.setAssistUnit2(null);
                    infoCon.setDeptLevel2vice2(null);
                    infoCon.setScid(wpInfo.getScid());
                    infoCon.setEndState("自办");
                    int i = wpInfoMapper.updateMainDeptByScid(infoCon);


                    wpInfo.setDeptLevel2(null);
                    wpInfo.setMainUnit(null);
                    wpInfo.setAssistUnit1(null);
                    wpInfo.setDeptLevel2vice1(null);

                    wpInfo.setAssistUnit2(null);
                    wpInfo.setDeptLevel2vice2(null);
                    wpInfo.setEndState("自办");
                }

                if ("工单归档".equals(wpInfo.getNextState())
                        ||"培训助理处理".equals(wpInfo.getNextState())){
                    WpInfo infoCon = new WpInfo();
                    infoCon.setDeptLevel2(null);
                    infoCon.setMainUnit(null);
                    infoCon.setAssistUnit1(null);
                    infoCon.setDeptLevel2vice1(null);
                    infoCon.setAssistUnit2(null);
                    infoCon.setDeptLevel2vice2(null);
                    infoCon.setScid(wpInfo.getScid());
                    infoCon.setEndState(null);
                    int i = wpInfoMapper.updateMainDeptByScid(infoCon);


                    wpInfo.setDeptLevel2(null);
                    wpInfo.setMainUnit(null);
                    wpInfo.setAssistUnit1(null);
                    wpInfo.setDeptLevel2vice1(null);

                    wpInfo.setAssistUnit2(null);
                    wpInfo.setDeptLevel2vice2(null);
                    wpInfo.setEndState(null);
                }

                if("督导处理".equals(wpInfo.getNextState())){
                    wpInfo.setEndState("流转");
                }
            }





        WpInfo info = wpInfoMapper.selectWpInfoByScid(wpInfo.getScid());
        String deptLevel2 = info.getDeptLevel2();

        if (StringUtils.isEmpty(wpInfo.getClass1())) {
            //内容分类为空
            wpInfo.setClass1(info.getClass1());
            wpInfo.setClass2(info.getClass2());
            wpInfo.setClass3(info.getClass3());
            wpInfo.setClass4(info.getClass4());
            wpInfo.setFiveMajorModules(info.getFiveMajorModules());
        }

        //如果单位为空字符串，直接为空
        if (StringUtils.isEmpty(wpInfo.getDeptLevel2())) {
            wpInfo.setDeptLevel2(null);
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (StringUtils.isNotEmpty(info.getCurrWorker())) {
            if (!user.getUserName().equals(info.getCurrWorker())) {
                SysUser sysUser = userMapper.selectUserByUserName(info.getCurrWorker());
                return AjaxResult.error("该工单" + sysUser.getNickName() + ",工号:" + sysUser.getCode() + "正在处理中，请稍后重试！");
            }
        }
        info.setState(wpInfo.getState());
        info.setNextState(wpInfo.getNextState());
        info.setLastmessage(wpInfo.getLastmessage());
        info.setBackClass(wpInfo.getBackClass());
        //坐席再次描述处理  之后，需要7个工作日  督导才能进行工单归档操作
        if ("工单归档".equals(wpInfo.getNextState()) && "督导审核".equals(wpInfo.getState())) {
            this.checkDdshTime(wpInfo);
        }

        this.checkFactAndAppeal(wpInfo);

        //修改工单标签
        if (StringUtils.isNotEmpty(wpInfo.getDictDataAll()) ||
                (wpInfo.getDictDataFlag() != null && wpInfo.getDictDataFlag())) {

            String join = StringUtils.join(wpInfo.getDictDataAll(), ",");
            wpInfo.setDictData(join);
        }

        //判断二次流转和二次处理流转和
        if ("二次处理-审核人处理".equals(wpInfo.getNextState())) {
            //二次处理
            wpInfo.setNextState("审核人处理");
            wpInfo.setEndState("流转");
            wpInfo.setIsTransfer("2");
            //二次处理（同一单位）需要退回的工单，只给予默认的5个工作日（即从退回之日开始计算）
            wpInfo.setTimelimite(5);
        } else if ("二次流转-审核人处理".equals(wpInfo.getNextState())) {
            //二次流转
            wpInfo.setNextState("审核人处理");
            wpInfo.setEndState("流转");
            wpInfo.setIsTransfer("3");
        }

        //判断是不是五大模块
        if (StringUtils.isNotEmpty(wpInfo.getClass2())) {
            //五大模块相关
            SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(wpInfo.getClass2()));
            if (StringUtils.isNotEmpty(sysCode.getFiveMajorModules())) {
                wpInfo.setFiveMajorModules(sysCode.getFiveMajorModules());
            }
        }
        if (StringUtils.isNotEmpty(wpInfo.getClass3())) {
            //五大模块相关
            SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(wpInfo.getClass3()));
            if (StringUtils.isNotEmpty(sysCode.getFiveMajorModules())) {
                wpInfo.setFiveMajorModules(sysCode.getFiveMajorModules());
            }
        }

        Date date = new Date();
        wpInfo.setUpdatetime(date);

        // 主办单位---放在上面会影响set deptLevel2
        String mainUnit = wpInfo.getMainUnit();
        //主办部门
        if (StringUtils.isNotEmpty(mainUnit)) {
            String[] split = mainUnit.split(",");
            wpInfo.setDeptLevel2(split[split.length - 1]);
            info.setDeptLevel2(split[split.length - 1]);
        }
        //协办部门1
        String assistUnit1 = wpInfo.getAssistUnit1();
        if (assistUnit1 != null) {
            String[] assistUnit1Split = assistUnit1.split(",");
            wpInfo.setDeptLevel2vice1(assistUnit1Split[assistUnit1Split.length - 1]);
            info.setDeptLevel2vice1(assistUnit1Split[assistUnit1Split.length - 1]);
        }

        //协办部门2
        String assistUnit2 = wpInfo.getAssistUnit2();
        if (assistUnit2 != null) {
            String[] assistUnit2Split = assistUnit2.split(",");
            wpInfo.setDeptLevel2vice2(assistUnit2Split[assistUnit2Split.length - 1]);
            info.setDeptLevel2vice2(assistUnit2Split[assistUnit2Split.length - 1]);
        }


        if ("承办单位处理".equals(wpInfo.getNextState())) {
            //代表承办单位未处理完成
            wpInfo.setCbdwComplete("0");
            if("2".equals(info.getIsTransfer()) && wpInfo.getMainUnit().equals(info.getMainUnit())){
                //二次处理（同一单位）需要退回的工单，只给予默认的5个工作日（即从退回之日开始计算）
                setWpInfoTime(wpInfo, date, 5);
            }else{
                setWpInfoTime(wpInfo, date, 10);
            }


            //TODO 发送短信
            wpInfo.setCustomerName(info.getCustomerName());
            wpInfo.setPhoneno(info.getPhoneno());

            //给承办单位发短信
//            if (wpInfo.getSmsflag() != null && "1".equals(wpInfo.getSmsflag())) {
            // 改成：发送短信不管选择是还是否，都需要发送给承办单位
//            if (wpInfo.getSmsflag() != null) {

                this.sendSmsToCBDW(wpInfo);
//            }


        }

        // 二次流转和二次处理 给承办单位发送短信
        if("审核人处理".equals(wpInfo.getState()) && "承办单位处理".equals(wpInfo.getNextState())){
            //轨迹表中查询上一条工单流转的next_state是二次流转-审核人处理还是二次处理-审核人处理
            WpHandleLog wpHandleLog = new WpHandleLog();
            wpHandleLog.setWpid(wpInfo.getWpid());
            WpHandleLog handleLog = wpHandleLogMapper.selectWpHandleLogList(wpHandleLog)
                    .stream()
                    .max(Comparator.comparing(WpHandleLog::getUpdateTime))
                    .orElse(null);
            if (handleLog == null) {
                throw new BaseException("工单轨迹有误！");
            }
            if("二次流转-审核人处理".equals(handleLog.getNextState())){
                log.info("二次流转-审核人处理 ---> 给单位下发短信");
                this.sendSmsToCBDW(wpInfo,"给承办单位发送");
            }else if("二次处理-审核人处理".equals(handleLog.getNextState())){
                log.info("二次处理-审核人处理 ---> 给单位下发短信");
                this.sendSmsToCBDW(wpInfo,"二次处理给承办单位发送");
            }
        }

        //发动短信给用户，将工单转到承办单位处理
        if (wpInfo.getSmsflag() != null && "1".equals(wpInfo.getSmsflag())) {

            String phoneno = info.getPhoneno();
            //TODO  发送短信生产暂时发送不了
            tsmsSendLogService.sendSmsBatch(phoneno, "工单流转到督导时，对用户提醒");
        }

        //只有承办单位处理的时候会多出这几个字段
        if ("承办单位处理".equals(wpInfo.getState())) {
            //督办件
            if ("0".equals(info.getIsSupervision())) {
                //如果是督办件必须到承办单位领导审核
                wpInfo.setNextState("承办单位领导审核");
            }

            //工单轨迹特有字段
            info.setSatisfied(wpInfo.getSatisfied());
            info.setReasonable(wpInfo.getReasonable());
            info.setSolved(wpInfo.getSolved());
            info.setBackClass(wpInfo.getBackClass());
        }
        //退单，收回
        if ("审核人收回工单".equals(wpInfo.getState()) || "1".equals(wpInfo.getBackState())) {
            WpInfo wpInfo1 = wpInfoMapper.selectWpInfoByScid(wpInfo.getScid());
            WpBackInfo wpBackInfo = new WpBackInfo();
            wpBackInfo.setWpid(wpInfo1.getWpid());
            wpBackInfo.setBackClass(wpInfo.getBackClass());
            //退单部门
            wpBackInfo.setBackDept(user.getDeptId().toString());
            wpBackInfo.setState(wpInfo.getState());
            wpBackInfo.setNextState(wpInfo.getNextState());
            wpBackInfo.setBackDate(date);
            wpBackInfo.setBackRefuse(wpInfo.getLastmessage());
            wpBackInfo.setOperator(user.getCode());
            wpBackInfo.setDeptLevel2(wpInfo1.getDeptLevel2());

            wpBackInfoMapper.insertWpBackInfo(wpBackInfo);

        }

        //插入轨迹表
        this.insertWpHandleLog(info);
        //工单回访需要进行记录回访信息
        if ("工单回访".equals(info.getState())) {
            this.insertWpVisitInfo(wpInfo);

        }
        //主办部门
        if (StringUtils.isEmpty(mainUnit)) {
            wpInfo.setDeptLevel2(null);
            info.setDeptLevel2(null);
        }

        if ("工单回访".equals(wpInfo.getNextState()) && (!"质检审核处理".equals(wpInfo.getState()))) {
            //代表承办单位处理完成
            wpInfo.setCbdwComplete("1");

        }

        if ("质检审核处理".equals(wpInfo.getState()) || "工单回访".equals(wpInfo.getState())) {
            List<String> causeList = wpInfo.getCauseList();

            if (StringUtils.isNotEmpty(causeList)) {
                String join = String.join(",", causeList);
                wpInfo.setCause(join);
            }
        }

        if ("是".equals(wpInfo.getIsSoundCases())) {
            //判断是否已经插入声音案例
            ZjSoundCase zjSoundCase = zjSoundCaseMapper.selectZjSoundCaseByWpid(info.getWpid());
            if (zjSoundCase == null) {
                info.setSubmitReason(wpInfo.getSubmitReason());
                addSoundCase(info);
            }
        }
        // 查询点击录音满意度
        WpEvaluateSatis wpEvaluateSatis = wpEvaluateSatisMapper.getByWpid(info.getWpid());
        if (wpEvaluateSatis != null) {
            wpInfo.setEvaluateSatis(wpEvaluateSatis.getEvaluateSatis());
        }
        if ("工单暂存".equals(info.getNextState())) {
            return AjaxResult.success(wpInfoMapper.updateWpInfoByZanCun(wpInfo));
        } else if ("承办单位处理".equals(info.getState())) {
            return AjaxResult.success(wpInfoMapper.updateCbclWpInfo(wpInfo));
        } else {
            // 只需要在待回访页面，如果是承办单位退单的，属于退单状态(用于待回访页面的查询)，待回访重新处理了,设置成0，
            if ("工单回访".equals(wpInfo.getState())) {
                wpInfo.setIsOrganizerBack(0);
            }
            return AjaxResult.success(wpInfoMapper.updateWpInfo(wpInfo));
        }

    }

    private void setWpInfoTime(WpInfo wpInfo, Date date, int days) {
        wpInfo.setTimelimite(days);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date timeBoundry = this.checkOntime(date, days);
        String format = simpleDateFormat.format(timeBoundry);
        wpInfo.setTimeBoundry(format);
    }


    //工单转到承办单位需要给承办单位用户发送短信
    public void sendSmsToCBDW(WpInfo wpInfo) {
        //转接到承办单位处理，需要发送短信给承办单位人员
        if (StringUtils.isNotEmpty(wpInfo.getDeptLevel2())) {

            List<TSmsUser> sysUsers = tSmsUserService.getSmsUserList(Long.valueOf(wpInfo.getDeptLevel2()));
            List<String> phonenos = sysUsers.stream()
                    .map(TSmsUser::getMobile)
                    .filter(StringUtils::isNotEmpty)
                    .collect(Collectors.toList());
            if (StringUtils.isNotEmpty(phonenos)) {

                String receivePhones = StringUtils.join(phonenos, ",");
                // 给主办单位发送短信
                tsmsSendLogService.sendSmsBatchOrganizedby(receivePhones, "给承办单位发送",
                        wpInfo.getCustomerName(), wpInfo.getPhoneno());

            }

        }
    }

    public void sendSmsToCBDW(WpInfo wpInfo,String dictLabel) {
        //转接到承办单位处理，需要发送短信给承办单位人员
        if (StringUtils.isNotEmpty(wpInfo.getDeptLevel2())) {

            List<TSmsUser> sysUsers = tSmsUserService.getSmsUserList(Long.valueOf(wpInfo.getDeptLevel2()));
            List<String> phonenos = sysUsers.stream()
                    .map(TSmsUser::getMobile)
                    .filter(StringUtils::isNotEmpty)
                    .collect(Collectors.toList());
            if (StringUtils.isNotEmpty(phonenos)) {

                String receivePhones = StringUtils.join(phonenos, ",");
                // 给主办单位发送短信
                tsmsSendLogService.sendSmsBatchOrganizedby(receivePhones, dictLabel,
                        wpInfo.getCustomerName(), wpInfo.getPhoneno());

            }

        }
    }

    /**
     * 增加声音案例
     */
    private void addSoundCase(WpInfo wpInfo) {
        // 添加声音案例
        ZjSoundCase zjSoundCase = new ZjSoundCase();
        zjSoundCase.setWpid(wpInfo.getWpid());
        zjSoundCase.setAcceptStatus("待采纳");
        zjSoundCase.setIsSoundCases("是");
        String code = SecurityUtils.getLoginUser().getUser().getCode();
        zjSoundCase.setCreateBy(code);
        zjSoundCase.setCreateTime(new Date());
        zjSoundCase.setSender(wpInfo.getSender());
        zjSoundCase.setSubmitReason(wpInfo.getSubmitReason());
        zjSoundCaseService.addZjSoundCase(zjSoundCase);
    }

    /**
     * 修改工单表(修改是否有责、是否投诉等信息)
     *
     * @param wpInfo 工单表
     * @return 结果
     */
    @Override
    public int updateWpInfo1(WpInfo wpInfo) {
        WpInfo info = wpInfoMapper.selectWpInfoByScid(wpInfo.getScid());
        if (StringUtils.isEmpty(wpInfo.getClass1())) {
            wpInfo.setClass1(info.getClass1());
            wpInfo.setClass2(info.getClass2());
            wpInfo.setClass3(info.getClass3());
            wpInfo.setClass4(info.getClass4());
            wpInfo.setFiveMajorModules(info.getFiveMajorModules());
        }
        return wpInfoMapper.updateWpInfo(wpInfo);
    }

    /**
     * 根据工单号修改工单表(是否声音案例)
     *
     * @param wpid 工单号
     * @return 结果
     */
    @Override
    public int updateWpInfo2(String wpid) {
        return wpInfoMapper.updateWpInfo2(wpid);
    }

    /**
     * 坐席再次处理页面转督导审核，没有满足七天，督导无法进行归档操作
     *
     * @param wpInfo
     */
    private void checkDdshTime(WpInfo wpInfo) {

        String wpid = wpInfo.getWpid();
        WpHandleLog wpHandleLog = new WpHandleLog();
        wpHandleLog.setWpid(wpid);
        wpHandleLog.setNextState("督导审核");
        wpHandleLog.setLastState("坐席再次描述处理");
        WpHandleLog handleLog = wpHandleLogMapper.selectWpHandleLogList(wpHandleLog)
                .stream()
                .max(Comparator.comparing(WpHandleLog::getUpdateTime))
                .orElse(null);
        if (handleLog == null) {
            throw new BaseException("工单轨迹有误！");
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        long year = calendar.get(Calendar.YEAR);
        WpHoliday wpHoliday = new WpHoliday();
        wpHoliday.setYearid(year);
        List<WpHoliday> wpHolidays = wpHolidayMapper.selectWpHolidayList(wpHoliday);


        List<String> dates = wpHolidays.stream()
                .map(WpHoliday::getDtime)
                .map(simpleDateFormat::format)
                .collect(Collectors.toList());

        Date timeSeven = wpInfoDeptService.checkOntime(handleLog.getUpdateTime(), daySeven, dates);
        Date date = new Date();
        if (date.compareTo(timeSeven) < 0) {
            throw new BaseException("坐席再次处理不足7个工作日，督导无法归档！");
        }

    }

    /**
     * 检测事实认定和诉求认定
     *
     * @param wpInfo
     */
    private void checkFactAndAppeal(WpInfo wpInfo) {
        if (StringUtils.isNotEmpty(wpInfo.getFact()) && (!"属实".equals(wpInfo.getFact()))) {
            if (StringUtils.isEmpty(wpInfo.getFactInfo())) {
                throw new BaseException("事实认定为" + wpInfo.getFact() + "时，，事实认定描述不能为空！");
            }
        }
        if (StringUtils.isNotEmpty(wpInfo.getAppeal()) && (!"诉求合理合法".equals(wpInfo.getAppeal()))) {
            if (StringUtils.isEmpty(wpInfo.getAppealInfo())) {
                throw new BaseException("诉求认定为" + wpInfo.getAppeal() + "时，诉求认定描述不能为空！");
            }
        }
    }

    /**
     * 插入回访记录
     *
     * @param wpInfo
     */
    private void insertWpVisitInfo(WpInfo wpInfo) {
        SysUser user = SecurityUtils.getLoginUser().getUser();

        WpVisitInfo wpVisitInfo = new WpVisitInfo();

        wpVisitInfo.setWpid(wpInfo.getWpid());

        wpVisitInfo.setCustomerName(wpInfo.getCustomerName());

        wpVisitInfo.setPhoneno(wpInfo.getPhoneno());
        //回访结果
        wpVisitInfo.setVisitResult(wpInfo.getVisitState());
        //回访工作编号
        wpVisitInfo.setVisitWorkNo(user.getCode());

        wpVisitInfo.setAcceptVisit(wpInfo.getAcceptVisit());
        //是否接受回访  0不接受，1接受
        //当时为什么会给默认值
       /* if (StringUtils.isNotEmpty(wpInfo.getAcceptVisit())) {
            wpVisitInfo.setAcceptVisit(wpInfo.getAcceptVisit());
        } else {
            wpVisitInfo.setAcceptVisit("1");
        }*/
        wpVisitInfo.setDeptLevel2(wpInfo.getDeptLevel2());
        /*if (StringUtils.isNotEmpty(wpInfo.getIssatisfied())) {
            wpVisitInfo.setIssatisfied(wpInfo.getIssatisfied());
        } else {
            wpVisitInfo.setIssatisfied("满意");
        }*/
        wpVisitInfo.setIssatisfied(wpInfo.getIssatisfied());
        wpVisitInfo.setIssatisfiedOther(wpInfo.getIssatisfiedOther());
        if (StringUtils.isNotEmpty(wpInfo.getIssatisfiedReason())) {
            wpVisitInfo.setIssatisfiedReason(wpInfo.getIssatisfiedReason());
        }
        wpVisitInfo.setIsReply(wpInfo.getIsReply());
        wpVisitInfo.setIsanswer(wpInfo.getIsanswer());
        wpVisitInfo.setVisitResult(wpInfo.getLastmessage());
        wpVisitInfo.setVisitTime(wpInfo.getUpdatetime());
        //政务类类型
        wpVisitInfo.setInfoType("vgwu");
        // 查询是否有回访记录
        WpVisitInfo visitInfo = wpVisitInfoMapper.selectWpVisitInfoByWpid(wpInfo.getWpid());
        // 没有数据就新增
        if (visitInfo == null) {
            wpVisitInfoMapper.insertWpVisitInfo(wpVisitInfo);
        } else {
            wpVisitInfo.setScid(visitInfo.getScid());
            wpVisitInfoMapper.updateWpVisitInfo(wpVisitInfo);
        }
//        wpVisitInfoMapper.insertWpVisitInfo(wpVisitInfo);
    }

    /**
     * 批量删除工单表
     *
     * @param scids 需要删除的工单表主键
     * @return 结果
     */
    @Override
    public int deleteWpInfoByScids(String[] scids) {
        return wpInfoMapper.deleteWpInfoByScids(scids);
    }

    /**
     * 删除工单表信息
     *
     * @param scid 工单表主键
     * @return 结果
     */
    @Override
    public int deleteWpInfoByScid(String scid) {
        return wpInfoMapper.deleteWpInfoByScid(scid);
    }

    @Override
    public String getWpId(String channel) {
        boolean flag = true;
        String wpId = "";
        //放置工单编号重复
        while (flag) {
            wpId = generateWpId(channel);
            WpInfo wpInfo = new WpInfo();
            wpInfo.setWpid(wpId);
            List<WpInfo> wpInfos = wpInfoMapper.selectWpInfoList(wpInfo);
            if (StringUtils.isEmpty(wpInfos)) {
                flag = false;
            }
        }
        return wpId;

    }

    @Override
    public List<WpInfo> findWpInfoListByPhone(String phoneno) {

        List<WpInfo> wpInfos = wpInfoMapper.selectWpInfoByPhoneno(phoneno);
        for (WpInfo wpInfo : wpInfos) {
            WpHandleLog wpHandleLog = new WpHandleLog();
            wpHandleLog.setLastState("承办单位处理");
            if (wpInfo != null) {
                wpHandleLog.setWpid(wpInfo.getWpid());
            }
            List<WpHandleLog> wpHandleLogs = wpHandleLogMapper.selectWpHandleLogList(wpHandleLog);
            WpHandleLog handleLog = wpHandleLogs.stream().max(Comparator.comparing(WpHandleLog::getUpdateTime)).orElse(null);
            if (handleLog != null && wpInfo != null) {
                wpInfo.setKlContentTitle(handleLog.getMessage());
            }
        }

        return wpInfos;
    }

    @Override
    public List<WpInfo> selectWpInfoListByPhoneAndNextState(WpInfo wpInfo) {
//        return wpInfoMapper.selectWpInfoList(wpInfo);
        return wpInfoMapper.selectWpInfoListByPhoneAndNextState(wpInfo);
    }


    /**
     * 查询导出集合
     *
     * @param wpInfo
     * @return
     */
    @Override
    public List<WpInfo> exportWpInfoList(WpInfo wpInfo) throws ParseException {

        List<String> districtAll = wpInfo.getDistrictAll();
        if (StringUtils.isNotEmpty(districtAll)) {
            for (int i = 0; i < districtAll.size(); i++) {
                if (i == 0) {
                    //区域
                    wpInfo.setDistrict(districtAll.get(i));
                }
                if (i == 1) {
                    //街道
                    wpInfo.setStreet(districtAll.get(i));
                }
                if (i == 2) {
                    //居委会
                    wpInfo.setCommittee(districtAll.get(i));

                }
            }
        }
        List<List<String>> classAllFind = wpInfo.getClassAllFind();
        //内容类别查询
        if (classAllFind == null || classAllFind.size() == 0) {
            wpInfo.setClassAll(null);
        } else {
            List<String> classAllCon = new ArrayList<>();
            for (List<String> strings : classAllFind) {
                classAllCon.add(strings.get(strings.size() - 1));
            }
            wpInfo.setClassAll(classAllCon);
        }

        List<WpInfo> wpInfos = wpInfoMapper.selectWpInfoList(wpInfo);
        for (WpInfo info : wpInfos) {

            String class1 = info.getClass1();
            String class2 = info.getClass2();
            String class3 = info.getClass3();
            String class4 = info.getClass4();

            StringBuffer name = new StringBuffer();

            if (StringUtils.isNotEmpty(class1)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class1));
                info.setMainNodename(sysCode.getNodename());
            }

            if (StringUtils.isNotEmpty(class2)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class2));
                name.append(sysCode.getNodename());
            }
            if (StringUtils.isNotEmpty(class3)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class3));
                name.append("/").append(sysCode.getNodename());
            }
            if (StringUtils.isNotEmpty(class4)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class4));
                name.append("/").append(sysCode.getNodename());
            }
            if (StringUtils.isNotEmpty(name)) {
                info.setChildNodeName(name.toString());
            }

            //标志位
            StringBuilder flagBit = new StringBuilder();
            //是否为退单
            if ("1".equals(info.getBackState())) {
                flagBit.append("退/");
            }
            //判断特殊，扬言（0特殊，1扬言）
            if ("0".equals(info.getSpecialState())) {
                flagBit.append("特/");
            } else if ("1".equals(info.getSpecialState())) {
                flagBit.append("扬/");
            }
            //判断督办，核办
            if ("0".equals(info.getIsSupervision())) {
                flagBit.append("督/");
            } else if ("1".equals(info.getIsSupervision())) {
                flagBit.append("核/");
            }
            String flagBitCon = flagBit.toString();
            if (StringUtils.isNotEmpty(flagBitCon)) {
                String substring = flagBitCon.substring(0, flagBitCon.length() - 1);
                info.setFlagBit(substring);
            }

            if ("0".equals(info.getReadFlag())) {
                info.setReadFlagName("未阅");
            } else {
                info.setReadFlagName("已阅");
            }
        }
        return wpInfos;

    }

    /**
     * 已处理列表
     *
     * @param wpInfo
     * @return
     */
    @Override
    public TableDataInfo selectprocessedWpInfoList(WpInfo wpInfo) throws ParseException {

        List<String> districtAll = wpInfo.getDistrictAll();
        if (StringUtils.isNotEmpty(districtAll)) {
            for (int i = 0; i < districtAll.size(); i++) {
                if (i == 0) {
                    //区域
                    wpInfo.setDistrict(districtAll.get(i));
                }
                if (i == 1) {
                    //街道
                    wpInfo.setStreet(districtAll.get(i));
                }
                if (i == 2) {
                    //居委会
                    wpInfo.setCommittee(districtAll.get(i));

                }
            }
        }
        List<List<String>> classAllFind = wpInfo.getClassAllFind();
        //内容类别查询
        if (classAllFind == null || classAllFind.size() == 0) {
            wpInfo.setClassAll(null);
        } else {
            List<String> classAllCon = new ArrayList<>();
            for (List<String> strings : classAllFind) {
                classAllCon.add(strings.get(strings.size() - 1));
            }
            wpInfo.setClassAll(classAllCon);
        }
        List<WpInfo> wpids;
        String prop = wpInfo.getProp();
        String order = wpInfo.getOrder();

        if ("审核人处理".equals(wpInfo.getLastState())) {

            String orderBy = UpperItemUtils.upperInfoName(order, prop);
            //排序字段
            String rowItem = UpperItemUtils.upperRowItem(prop);
            wpInfo.setRowItem(rowItem);
            wpInfo.setOrderBy(orderBy);
            wpids = wpInfoMapper.selectReviewerWpInfoList(wpInfo);
        } else if ("督导处理".equals(wpInfo.getLastState())) {
            wpInfo.setLastState("督导处理");

            if ("mainUnitName".equals(prop)) {
                prop = "mainUnit";
            }
            String orderBy = UpperItemUtils.upperInfoName(order, prop);
            //排序字段
            String rowItem = UpperItemUtils.upperRowItem(prop);
            String processedRowItem = UpperItemUtils.upperProcessedRowItem(prop);
            wpInfo.setRowItem(rowItem);
            wpInfo.setProcessedRowItem(processedRowItem);
            wpInfo.setOrderBy(orderBy);

            wpids = wpInfoMapper.selectProcessedWpInfoList(wpInfo);
        } else if ("承办单位处理".equals(wpInfo.getLastState())) {
           /* if ("mainUnitName".equals(prop)) {
                prop = "mainUnit";
            }
            String orderBy = UpperItemUtils.upperInfoName(order, prop);
            //排序字段
            String rowItem = UpperItemUtils.upperRowItem(prop);
            String processedRowItem = UpperItemUtils.upperProcessedRowItem(prop);
            wpInfo.setRowItem(rowItem);
            wpInfo.setProcessedRowItem(processedRowItem);
            wpInfo.setOrderBy(orderBy);*/

            wpids = wpInfoMapper.selectProcessedCBWpInfoList(wpInfo);
        } else {
            if ("坐席处理".equals(wpInfo.getLastState())) {
                List<String> lasetStates = new ArrayList<String>();
                lasetStates.add("坐席处理");
                lasetStates.add("坐席受理");
                lasetStates.add("坐席再次描述处理");
                lasetStates.add("工单暂存");
                wpInfo.setLastStates(lasetStates);
                wpInfo.setLastState(null);
            }
            if ("mainUnitName".equals(prop)) {
                prop = "mainUnit";
            }
            String orderBy = UpperItemUtils.upperInfoName(order, prop);
            //排序字段
            String rowItem = UpperItemUtils.upperRowItem(prop);
            String processedRowItem = UpperItemUtils.upperProcessedRowItem(prop);
            wpInfo.setRowItem(rowItem);
            wpInfo.setProcessedRowItem(processedRowItem);
            wpInfo.setOrderBy(orderBy);

            wpids = wpInfoMapper.selectProcessedWpInfoList(wpInfo);
        }
        if (wpids.size() == 0) {
            //无数据，直接返回
            return getDataTable(new ArrayList<>(), wpids);
        }

        List<String> collect = wpids.stream().map(WpInfo::getWpid).collect(Collectors.toList());
        WpInfo infoCon = new WpInfo();
        infoCon.setOrderBy(wpInfo.getOrderBy());
        infoCon.setWpids(collect);
        List<WpInfo> wpinfos = wpInfoMapper.selectWpInfoByWpidsOrderBy(infoCon);

        SysUser user = SecurityUtils.getLoginUser().getUser();
        for (WpInfo info : wpinfos) {
            //设置 issatisfied 回访满意度 查询是否有回访记录
            if (StringUtils.isNotEmpty(wpInfo.getIssatisfied())) {
                info.setIssatisfied(wpInfo.getIssatisfied());
            } else {
                WpVisitInfo wpVisitInfo = wpVisitInfoMapper.selectWpVisitInfoByWpid(info.getWpid());
                if (wpVisitInfo != null) {
                    info.setIssatisfied(wpVisitInfo.getIssatisfied());
                }
            }

            if ("工单归档".equals(info.getNextState())) {
                WpHandleLog wpHandleLog = new WpHandleLog();
                wpHandleLog.setNextState("工单归档");
                wpHandleLog.setWpid(info.getWpid());
                WpHandleLog handleLog = wpHandleLogMapper.selectWpHandleLogList(wpHandleLog).stream().findAny().orElse(null);
                if (handleLog != null) {
                    info.setArchiveTime(handleLog.getUpdateTime());
                }

            }
            if (StringUtils.isNotEmpty(info.getSender())) {
                SysUser sysUser = userMapper.selectUserByCode(info.getSender());
                if (sysUser != null) {
                    info.setInitiatorName(sysUser.getNickName());
                }

            }

            info.setRevokeFlag(false);
            if (("督导处理".equals(info.getNextState()) || "培训助理处理".equals(info.getNextState()) || "质检审核处理".equals(info.getNextState()))
                    && user.getCode().equals(info.getCode()) && "0".equals(info.getReadFlag())) {
                info.setRevokeFlag(true);
            }

            if (StringUtils.isNotEmpty(info.getDeptLevel2())) {


                SysDept sysDept = sysDeptMapper.selectDeptById(Long.valueOf(info.getDeptLevel2()));
                if (sysDept != null) {
                    info.setMainUnitName(sysDept.getDeptName());
                }

            }

            String class1 = info.getClass1();
            String class2 = info.getClass2();
            String class3 = info.getClass3();
            String class4 = info.getClass4();

            StringBuffer name = new StringBuffer();

            if (StringUtils.isNotEmpty(class1)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class1));
                if (sysCode != null) {
                    info.setMainNodename(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(class2)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class2));
                if (sysCode != null) {
                    name.append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(class3)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class3));
                if (sysCode != null) {
                    name.append("/").append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(class4)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class4));
                if (sysCode != null) {
                    name.append("/").append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(name)) {
                info.setChildNodeName(name.toString());
            }
            if ("承办单位处理".equals(wpInfo.getLastState())) {
                WpHandleLog wpHandleLog = new WpHandleLog();
                wpHandleLog.setWpid(info.getWpid());
                wpHandleLogMapper.selectWpHandleLogList(wpHandleLog)
                        .stream()
                        .filter(handlog -> "承办单位处理".equals(handlog.getNextState()))
                        .max(Comparator.comparing(WpHandleLog::getUpdateTime))
                        .ifPresent(anElse -> info.setCalltime(anElse.getUpdateTime()));
            }

            String cbdwComplete = info.getCbdwComplete();
            if (StringUtils.isNotEmpty(cbdwComplete)) {
                //已完成
                if (cbdwComplete.equals("1")) {
                    info.setResidue("已完成");
                } else if (cbdwComplete.equals("0")) {
                    // 老数据的处理方式--2025-09-10
                    if ("工单归档".equals(info.getNextState())) {
                        info.setResidue("已完成");
                    }else {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String timeBoundry = info.getTimeBoundry();
                        if (StringUtils.isNotEmpty(timeBoundry)) {
                            String residueDay = checkResidueDay(simpleDateFormat.parse(timeBoundry));
                            info.setResidue(residueDay);
                        }
                    }
                }
            }
        }
        return getDataTable(wpinfos, wpids);
    }

    @Override
    public WpInfo getWpInfoDetailed(WpInfo wpInfo) {
        WpInfo info = wpInfoMapper.selectWpInfoByScid(wpInfo.getScid());
        if (info == null) {
            throw new BaseException("未查询到工单");
        }
        String fileno = wpInfo.getFileno();
        if (fileno != null) {
            String[] split = wpInfo.getFileno().split(",");
            if (split.length > 0) {
                List<SysMiniFile> sysMiniFiles = sysMiniFileMapper.selectSysMiniFileByIds(split);
                wpInfo.setSysMiniFiles(sysMiniFiles);
            }
        }
        WpHandleLog wpHandleLog = new WpHandleLog();
        wpHandleLog.setWpid(info.getWpid());
        List<WpHandleLog> wpHandleLogs = wpHandleLogMapper.selectWpHandleLogList(wpHandleLog);

        //循环轨迹表，赋值满意度等字段
        for (WpHandleLog handleLog : wpHandleLogs) {
            SysUser user = userMapper.selectUserByCode(handleLog.getOperator());
            if (user != null) {
                handleLog.setNickName(user.getNickName());
            }

            if ("承办单位处理".equals(handleLog.getLastState())) {
                info.setSatisfied(handleLog.getSatisfied());
                info.setReasonable(handleLog.getReasonable());
                info.setSolved(handleLog.getSolved());
            }
            if ("工单回访".equals(handleLog.getLastState())) {

                WpVisitInfo wpVisitInfo = wpVisitInfoMapper.selectWpVisitInfoByWpid(wpInfo.getWpid());

                info.setAcceptVisit(wpVisitInfo.getAcceptVisit());
                info.setIsanswer(wpVisitInfo.getIsanswer());
                info.setIssatisfied(wpVisitInfo.getIssatisfied());
                info.setIssatisfiedReason(wpVisitInfo.getIssatisfiedReason());
                info.setIssatisfiedOther(wpVisitInfo.getIssatisfiedOther());
                info.setIsReply(wpVisitInfo.getIsReply());
            }
        }
        //轨迹列表
        info.setWpHandleLogs(wpHandleLogs);

        return info;
    }

    @Override
    public int updateWpinfoRead(WpInfo wpInfo) {
        return wpInfoMapper.updateWpinfoRead(wpInfo);
    }

    /**
     * 回访流程，批量处理
     *
     * @param wpInfoVO
     */
    @Override
    public AjaxResult batchingWpInfos(WpInfoVO wpInfoVO) {

        SysUser user = SecurityUtils.getLoginUser().getUser();
        String scids = wpInfoVO.getScids();
        String[] split = scids.split(",");
        Date date = new Date();
        List<String> wpids = new ArrayList<>();
        List<String> nickNames = new ArrayList<>();
        long currTime = System.currentTimeMillis();
        for (String scid : split) {
            WpInfo info = wpInfoMapper.selectWpInfoByScid(scid);

            if (StringUtils.isNotEmpty(info.getCurrWorker()) && info.getCurrWorkTime() != null) {
                // 如果超过15分钟 当前处理人和时间
                long overTimeMin = (currTime - info.getCurrWorkTime()) / 1000L / 60L;
                boolean flag = overTimeMin < EXPTIME;
                if (flag && !user.getUserName().equals(info.getCurrWorker())) {
                    SysUser sysUser = userMapper.selectUserByUserName(info.getCurrWorker());
                    //代表其他人打开了该工单，正在处理中
                    wpids.add(info.getWpid());
                    nickNames.add(sysUser.getNickName());
                    continue;
                }
            }
            info.setState(info.getNextState());
            info.setNextState(wpInfoVO.getNextState());

            info.setReadFlag(wpInfoVO.getReadFlag());
            //最新处理描述
            info.setLastmessage("无需回访");
            info.setUpdatetime(date);
            info.setIsSoundCases(wpInfoVO.getIsSoundCases());
            if ("是".equals(wpInfoVO.getIsSoundCases())) {
                //判断是否已经插入声音案例
                ZjSoundCase zjSoundCase = zjSoundCaseMapper.selectZjSoundCaseByWpid(info.getWpid());
                if (zjSoundCase == null) {
                    info.setSubmitReason(wpInfoVO.getSubmitReason());
                    addSoundCase(info);
                }
                //addSoundCase(info);
            }
            //插入回访表
            this.insertWpVisitInfo(info);
            //插入轨迹表
            this.insertWpHandleLog(info);
            wpInfoMapper.updateWpInfo(info);

        }
        if (StringUtils.isNotEmpty(wpids)) {
            String wpidJoin = String.join(",", wpids);
            String nickJoin = String.join(",", nickNames);
            return AjaxResult.success("工单编号为：" + wpidJoin + ",正再被" + nickJoin + "处理中");
        }
        return AjaxResult.success("操作成功！");
    }

    @Override
    public TableDataInfo selectVisitWpInfoList(WpInfo wpInfo) {
        //已经回访
        wpInfo.setVisitState("1");
        if ("0".equals(wpInfo.getAcceptVisit())) {
            wpInfo.setVisitUnStatus("0");
        }
        if ("1".equals(wpInfo.getAcceptVisit())) {
            wpInfo.setVisitStatus("0");
        }

        //排序相关
        String order = wpInfo.getOrder();
        String prop = wpInfo.getProp();
        String orderBy = UpperItemUtils.upperInfoName(order, prop);
        //排序字段
        String rowItem = UpperItemUtils.upperRowItem(prop);


        wpInfo.setRowItem(rowItem);

        wpInfo.setOrderBy(orderBy);
        List<WpInfo> wpids = wpVisitInfoMapper.selectWpVisitInfoWpids(wpInfo);
        if (wpids.size() == 0) {
            List<WpInfo> wpInfos = new ArrayList<>();
            return getDataTable(wpInfos, wpids);
        }
        WpInfo infoCon = new WpInfo();
        List<String> collect = wpids.stream().map(WpInfo::getWpid).collect(Collectors.toList());
        infoCon.setWpids(collect);

        String s = UpperItemUtils.upperInfoName(order, prop);
        if (!"issatisfied".equals(prop)) {
            infoCon.setOrderBy(s);
        }


        List<WpInfo> wpInfos = wpInfoMapper.selectWpInfoCountListByWpids(infoCon);

        for (WpInfo info : wpInfos) {

            if (StringUtils.isNotEmpty(wpInfo.getIssatisfied())) {
                info.setIssatisfied(wpInfo.getIssatisfied());
            } else {
                WpVisitInfo wpVisitInfo = wpVisitInfoMapper.selectWpVisitInfoByWpid(info.getWpid());
                if (wpVisitInfo != null) {
                    info.setIssatisfied(wpVisitInfo.getIssatisfied());
                }

            }

            if ("issatisfied".equals(prop) && StringUtils.isNotEmpty(order)) {
                if ("满意".equals(info.getIssatisfied())) {
                    info.setIssatisfiedWeight(1);
                } else if ("一般".equals(info.getIssatisfied())) {
                    info.setIssatisfiedWeight(2);
                } else if ("不满意".equals(info.getIssatisfied())) {
                    info.setIssatisfiedWeight(3);
                } else if (StringUtils.isEmpty(info.getIssatisfied())) {
                    info.setIssatisfiedWeight(4);
                }
            }


        }
        //评价满意度排序
        if ("issatisfied".equals(prop) && StringUtils.isNotEmpty(order)) {
            if ("descending".equals(order)) {
                List<WpInfo> infos = wpInfos.stream()
                        .sorted(Comparator.comparing(WpInfo::getIssatisfiedWeight))
                        .collect(Collectors.toList());
                return getDataTable(infos, wpids);
            } else {
                List<WpInfo> infosCon = wpInfos.stream()
                        .sorted(Comparator.comparing(WpInfo::getIssatisfiedWeight).reversed())
                        .collect(Collectors.toList());
                return getDataTable(infosCon, wpids);
            }
        }

        return getDataTable(wpInfos, wpids);
    }

    @Override
    public WpInfo getProcessedHandleWpinfo(ProcessedWpinfoVO processedWpinfoVO) {
        WpInfo wpInfo = wpInfoMapper.selectWpInfoByScid(processedWpinfoVO.getScid());
        if (wpInfo == null) {
            throw new BaseException("未查询到工单");
        }
        String fileno = wpInfo.getFileno();
        if (fileno != null) {
            String[] split = wpInfo.getFileno().split(",");
            if (split.length > 0) {
                List<SysMiniFile> sysMiniFiles = sysMiniFileMapper.selectSysMiniFileByIds(split);
                wpInfo.setSysMiniFiles(sysMiniFiles);
            }
        }
        WpHandleLog wpHandleLog = new WpHandleLog();
        wpHandleLog.setWpid(wpInfo.getWpid());
        List<WpHandleLog> wpHandleLogs = wpHandleLogMapper.selectWpHandleLogList(wpHandleLog);
        if (!wpHandleLogs.isEmpty()) {
            for (WpHandleLog handleLog : wpHandleLogs) {
                SysUser user = userMapper.selectUserByCode(handleLog.getOperator());
                if (user != null) {
                    handleLog.setNickName(user.getNickName());
                }

            }
            wpInfo.setWpHandleLogs(wpHandleLogs);
            if ("已回访".equals(processedWpinfoVO.getProcessedType())) {

                WpVisitInfo wpVisitInfo = wpVisitInfoMapper.selectWpVisitInfoByWpid(wpInfo.getWpid());

                wpInfo.setAcceptVisit(wpVisitInfo.getAcceptVisit());
                wpInfo.setIsanswer(wpVisitInfo.getIsanswer());
                wpInfo.setIssatisfied(wpVisitInfo.getIssatisfied());
                wpInfo.setIssatisfiedReason(wpVisitInfo.getIssatisfiedReason());
                wpInfo.setIssatisfiedOther(wpVisitInfo.getIssatisfiedOther());
                wpInfo.setIsReply(wpVisitInfo.getIsReply());
            }

        }
        return wpInfo;
    }

    /**
     * 审核人催单
     *
     * @param wpInfo
     * @return
     */
    @Transactional
    @Override
    public int reminderEdit(WpInfo wpInfo) {

        WpInfo info = wpInfoMapper.selectWpInfoByScid(wpInfo.getScid());
        if (StringUtils.isEmpty(wpInfo.getClass1())) {
            wpInfo.setClass1(info.getClass1());
            wpInfo.setClass2(info.getClass2());
            wpInfo.setClass3(info.getClass3());
            wpInfo.setClass4(info.getClass4());
            wpInfo.setFiveMajorModules(info.getFiveMajorModules());
        }
        //催单次数
        wpInfo.setHurryCount(info.getHurryCount() + 1);
        //催单时间
        wpInfo.setHurryTime(new Date());
        //催单状态
        wpInfo.setHurryFlag("1");

        wpInfo.setDeptLevel2(info.getDeptLevel2());

        wpInfo.setWpid(info.getWpid());
        // 查询部门人员的手机号，用于发送催单短信
        List<TSmsUser> sysUsers = tSmsUserService.getSmsUserList(Long.valueOf(info.getDeptLevel2()));
        List<String> phonenos = sysUsers.stream()
                .map(TSmsUser::getMobile)
                .filter(StringUtils::isNotEmpty)
                .collect(Collectors.toList());
        if (StringUtils.isNotEmpty(phonenos)) {
            String receivePhones = StringUtils.join(phonenos, ",");
            // 给三级承办单位催单短信
            tsmsSendLogService.sendSmsBatch(receivePhones, "给三级承办单位催单短信");
        }
        // 已经催单的表
        this.insertWpHurryLog(wpInfo);
        // 修改工单，表示已经催单了
        return wpInfoMapper.updateWpInfo(wpInfo);
    }

    private void insertWpHurryLog(WpInfo wpInfo) {

        WpHurryLog wpHurryLog = new WpHurryLog();

        wpHurryLog.setWpid(wpInfo.getWpid());

        wpHurryLog.setHurryName(wpInfo.getHurryName());
        wpHurryLog.setHurryFlag(wpInfo.getHurryFlag());
        wpHurryLog.setHurryTime(wpInfo.getHurryTime());
        wpHurryLog.setHurryReason(wpInfo.getHurryReason());

        wpHurryLog.setDeptLevel2(wpInfo.getDeptLevel2());

        wpHurryLog.setCreateTime(wpInfo.getHurryTime());
        wpHurryLog.setUpdateTime(wpInfo.getHurryTime());

        wpHurryLogMapper.insertWpHurryLog(wpHurryLog);


    }

    /**
     * 审核人延期处理
     *
     * @param wpInfo
     * @return
     */
    @Override
    public int extensionEdit(WpInfo wpInfo) {

        WpInfo info = wpInfoMapper.selectWpInfoByScid(wpInfo.getScid());
        info.setUpdatetime(new Date());

        info.setState("延期处理");
        //1代表延期
        info.setExtensionStatus("1");
        //将延期理由进行保存
        info.setLastmessage(wpInfo.getLastmessage());
        info.setExtensionTime(wpInfo.getTimeBoundry());

        this.insertWpHandleLog(info);
        //工单表的处理理由还是保存之前完成的理由
        info.setLastmessage(null);
        info.setTimeBoundry(wpInfo.getTimeBoundry());
        return wpInfoMapper.updateWpInfo(info);
    }

    /**
     * 逻辑删除工单
     *
     * @param wpInfo
     * @return
     */
    @Override
    public int updateDelFlag(WpInfo wpInfo) {

        Date date = new Date();

        WpUpdateLog wpUpdateLog = new WpUpdateLog();
        wpInfo.setWpid(wpInfo.getWpid());
        wpUpdateLog.setCreateTime(date);
        wpUpdateLog.setOperateName(SecurityUtils.getUsername());
        wpUpdateLog.setOperateState("删除");
        wpUpdateLog.setUpdateTime(date);
        //保存逻辑删除记录
        wpUpdateLogMapper.insertWpUpdateLog(wpUpdateLog);

        wpInfo.setUpdatetime(date);

        return wpInfoMapper.updateDelFlag(wpInfo);
    }

    @Override
    public PrintWpInfoVO getPrintWpInfo(String scid) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        WpInfo info = wpInfoMapper.selectWpInfoByScid(scid);
        if (info == null) {
            throw new BaseException("工单不存在");
        }

        PrintWpInfoVO printWpInfoVO = new PrintWpInfoVO();

        printWpInfoVO.setCustomerName(info.getCustomerName());
        printWpInfoVO.setAddress(info.getAddress());
        printWpInfoVO.setCalltime(info.getCalltime() != null ? simpleDateFormat.format(info.getCalltime()) : "");
        printWpInfoVO.setPhoneno(info.getPhoneno());
        printWpInfoVO.setSummary(info.getSummary());
        printWpInfoVO.setUpdatetime(info.getUpdatetime() != null ? simpleDateFormat.format(info.getUpdatetime()) : "");
        printWpInfoVO.setNote(info.getNote());

        if (StringUtils.isNotEmpty(info.getDeptLevel2())) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Long.valueOf(info.getDeptLevel2()));
            if (sysDept != null) {
                printWpInfoVO.setDeptLevel2Name(sysDept.getDeptName());
            }

        }

        if (StringUtils.isNotEmpty(info.getDeptLevel2vice1())) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Long.valueOf(info.getDeptLevel2vice1()));
            if (sysDept != null) {
                printWpInfoVO.setDeptLevel2vice1Name(sysDept.getDeptName());
            }

        }

        if (StringUtils.isNotEmpty(info.getDeptLevel2vice2())) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Long.valueOf(info.getDeptLevel2vice2()));
            if (sysDept != null) {
                printWpInfoVO.setDeptLevel2vice2Name(sysDept.getDeptName());
            }

        }

        WpHandleLog wpHandleLog = new WpHandleLog();
        wpHandleLog.setWpid(info.getWpid());

        List<WpHandleLog> wpHandleLogs = wpHandleLogMapper.selectWpHandleLogList(wpHandleLog);

        for (WpHandleLog handleLog : wpHandleLogs) {
            if ("承办单位处理".equals(handleLog.getLastState())) {
                SysUser sysUser = userMapper.selectUserByCode(handleLog.getOperator());
                if (sysUser != null) {
                    printWpInfoVO.setOperator(sysUser.getNickName());
                }
                printWpInfoVO.setOperatorMessage(handleLog.getMessage());
                printWpInfoVO.setOperatorTime(handleLog.getUpdateTime() != null ? simpleDateFormat.format(handleLog.getUpdateTime()) : "");

            }
            if ("承办单位领导审核".equals(handleLog.getLastState())) {
                printWpInfoVO.setOperatorLd(handleLog.getOperator());
                printWpInfoVO.setOperatorLdMessage(handleLog.getMessage());
                printWpInfoVO.setOperatorLdTime(handleLog.getUpdateTime() != null ? simpleDateFormat.format(handleLog.getUpdateTime()) : "");
            }
        }

        return printWpInfoVO;
    }

    @Override
    public WpInfoEchartsVO getWpInfoEcharts() {

        WpInfoEchartsVO wpInfoEchartsVO = new WpInfoEchartsVO();

        List<Integer> lastMonth = new ArrayList<>();

        List<Integer> currentMonth = new ArrayList<>();

        List<Integer> month = new ArrayList<>();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        List<String> localDates = new ArrayList<>();

        YearMonth yearMonth = YearMonth.now();
        int dayLengthCon = yearMonth.lengthOfMonth();

        for (int i = 1; i <= dayLengthCon; i++) {

            LocalDate localDate = yearMonth.atDay(i);
            String localDateNowStr = localDate.format(formatter);
            localDates.add(localDateNowStr);
        }

        Map<String, Integer> mapCon = wpInfoMapper.getWpInfoEcharts(localDates).stream()
                .collect(Collectors.toMap(EchartsVO::getStarttime, EchartsVO::getWpInfoNum));
        ;

        for (String localDate : localDates) {
            Integer count = mapCon.get(localDate);
            if (count != null) {
                currentMonth.add(count);
            } else {
                currentMonth.add(0);
            }
        }

        //上个月
        YearMonth yearMonthLast = yearMonth.minusMonths(1);

        int dayLength = yearMonthLast.lengthOfMonth();

        List<String> localDatesLast = new ArrayList<>();

        for (int i = 1; i <= dayLength; i++) {

            LocalDate localDate = yearMonthLast.atDay(i);
            String localDateNowStr = localDate.format(formatter);
            localDatesLast.add(localDateNowStr);
        }

        Map<String, Integer> map = wpInfoMapper.getWpInfoEcharts(localDatesLast).stream()
                .collect(Collectors.toMap(EchartsVO::getStarttime, EchartsVO::getWpInfoNum));
        ;

        for (String localDate : localDatesLast) {
            Integer count = map.get(localDate);
            if (count != null) {
                lastMonth.add(count);
            } else {
                lastMonth.add(0);
            }
        }

        int size = Math.max(dayLength, dayLengthCon);


        for (int i = 1; i <= size; i++) {
            month.add(i);
        }
        wpInfoEchartsVO.setLastMonth(lastMonth);
        wpInfoEchartsVO.setCurrentMonth(currentMonth);
        wpInfoEchartsVO.setMonth(month);
        return wpInfoEchartsVO;
    }

    /**
     * 审核人未审核列表
     *
     * @param wpInfo
     * @return
     */
    @Override
    public List<WpInfo> selectReviewerUntreatedList(WpInfo wpInfo) throws ParseException {

        //审核人为审核页面有两个状态
        if ("回访后审核人处理/审核人处理".equals(wpInfo.getNextState())) {
            List<String> nextStateList = Arrays.stream(wpInfo.getNextState().split("/")).collect(Collectors.toList());
            wpInfo.setNextStateList(nextStateList);
            wpInfo.setNextState(null);
        }
        //内容分类查询条件
        List<List<String>> classAllFind = wpInfo.getClassAllFind();
        //内容分类查询
        if (StringUtils.isEmpty(classAllFind)) {
            wpInfo.setClassAll(null);
        } else {
            List<String> classAllCon = new ArrayList<>();
            for (List<String> strings : classAllFind) {
                classAllCon.add(strings.get(strings.size() - 1));
            }
            wpInfo.setClassAll(classAllCon);
        }


        //排序相关
        String order = wpInfo.getOrder();
        String prop = wpInfo.getProp();
        String orderBy = UpperItemUtils.recoverUpperName(order, prop);

        wpInfo.setOrderBy(orderBy);
        List<WpInfo> wpInfos = wpInfoMapper.selectReviewerUntreatedList(wpInfo);
        for (WpInfo info : wpInfos) {
            WpHandleLog log = new WpHandleLog();
            log.setWpid(info.getWpid());
            log.setNextState("承办单位处理");
            List<WpHandleLog> wpHandleLogs = wpHandleLogMapper.selectWpHandleLogList(log);
            wpHandleLogs.stream()
                    .max(Comparator.comparing(WpHandleLog::getUpdateTime))
                    .ifPresent(wpHandleLog -> info.setCbdwDate(wpHandleLog.getUpdateTime()));
            if (StringUtils.isNotEmpty(info.getDeptLevel2())) {
                SysDept sysDept = sysDeptMapper.selectDeptById(Long.valueOf(info.getDeptLevel2()));
                if (sysDept != null) {
                    info.setMainUnitName(sysDept.getDeptName());
                }

            }
            //工单是否在处理中 true为处理中
            info.setProcessing(false);
            if (info.getCurrWorkTime() != null) {
                long currTime = System.currentTimeMillis();
                // 如果超过15分钟 当前处理人和时间
                long overTimeMin = (currTime - info.getCurrWorkTime()) / 1000L / 60L;
                boolean isOvertime = overTimeMin > EXPTIME;
                if (!isOvertime) {
                    info.setProcessing(true);
                }

            }
            String class1 = info.getClass1();
            String class2 = info.getClass2();
            String class3 = info.getClass3();
            String class4 = info.getClass4();

            StringBuffer name = new StringBuffer();

            if (StringUtils.isNotEmpty(class1)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class1));
                if (sysCode != null) {
                    info.setMainNodename(sysCode.getNodename());
                }
            }

            if (StringUtils.isNotEmpty(class2)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class2));
                if (sysCode != null) {
                    name.append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(class3)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class3));
                if (sysCode != null) {
                    name.append("/").append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(class4)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class4));
                if (sysCode != null) {
                    name.append("/").append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(name)) {
                info.setChildNodeName(name.toString());
            }
            String cbdwComplete = info.getCbdwComplete();
            if (StringUtils.isNotEmpty(cbdwComplete)) {
                //已完成
                if (cbdwComplete.equals("1")) {
                    info.setResidue("已完成");
                } else if (cbdwComplete.equals("0")) {
                    // 老数据的处理方式--2025-09-10
                    if ("工单归档".equals(info.getNextState())) {
                        info.setResidue("已完成");
                    }else {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String timeBoundry = info.getTimeBoundry();
                        if (StringUtils.isNotEmpty(timeBoundry)) {
                            String residueDay = checkResidueDay(simpleDateFormat.parse(timeBoundry));
                            info.setResidue(residueDay);
                        }
                    }
                }
            }
        }

        return wpInfos;

    }

    /**
     * 坐席派发
     *
     * @param wpInfo
     * @return
     */
    @Override
    public int allocationWpInfo(WpInfo wpInfo) {
        WpInfo info = wpInfoMapper.selectWpInfoByScid(wpInfo.getScid());
        info.setSender(wpInfo.getSender());
        info.setUpdatetime(new Date());
        info.setCode(wpInfo.getSender());
        info.setSellReason(wpInfo.getSellReason());
        this.insertWpHandleLogByAllocation(info);

        return wpInfoMapper.updateWpInfo(info);
    }

    public void insertWpHandleLogByAllocation(WpInfo wpInfo) {

        Date date = new Date();
        //添加完成后，需要将在主轨迹表添加轨迹数据
        WpHandleLog wpHandleLog = new WpHandleLog();
        //登录人员信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        wpHandleLog.setWpid(wpInfo.getWpid());
        wpHandleLog.setOperator(user.getCode());
        wpHandleLog.setMessage(wpInfo.getSellReason());
        wpHandleLog.setSummary(wpInfo.getSummary());
        //部门id
        wpHandleLog.setDepartment(user.getDeptId().toString());
        wpHandleLog.setLastState(wpInfo.getState());
        wpHandleLog.setNextState("再次派发工单");
        //派发原因
        wpHandleLog.setMessage(wpInfo.getSellReason());

        wpHandleLog.setUpdateTime(date);

        String processId = wpHandleLogMapper.getWpHandleLogId();
        wpHandleLog.setProcessId("SQ" + processId);
        wpHandleLogMapper.insertWpHandleLog(wpHandleLog);

    }

    @Override
    public TableDataInfo getManageWpListAll(WpInfo wpInfo) throws ParseException {
        //全部工单，只查询已经归档的工单
        List<String> districtAll = wpInfo.getDistrictAll();
        //居委会查询
        if (StringUtils.isNotEmpty(districtAll)) {
            for (int i = 0; i < districtAll.size(); i++) {
                if (i == 0) {
                    //区域
                    wpInfo.setDistrict(districtAll.get(i));
                }
                if (i == 1) {
                    //街道
                    wpInfo.setStreet(districtAll.get(i));
                }
                if (i == 2) {
                    //居委会
                    wpInfo.setCommittee(districtAll.get(i));

                }
            }
        }
        if (StringUtils.isNotEmpty(wpInfo.getIsTransfer())) {
            if ("自办".equals(wpInfo.getEndState())) {
                return getDataTable(new ArrayList<>(), new ArrayList<>());
            }
            if (StringUtils.isEmpty(wpInfo.getEndState()) && "1".equals(wpInfo.getIsTransfer())) {
                wpInfo.setEndState("流转");
            }
        }
        //内容分类查询条件
        List<List<String>> classAllFind = wpInfo.getClassAllFind();

        //内容分类查询
        if (StringUtils.isEmpty(classAllFind)) {
            wpInfo.setClassAll(null);
        } else {
            List<String> classAllCon = new ArrayList<>();
            for (List<String> strings : classAllFind) {
                classAllCon.add(strings.get(strings.size() - 1));
            }
            wpInfo.setClassAll(classAllCon);
        }
        String prop = wpInfo.getProp();
        String order = wpInfo.getOrder();
        String orderBy = UpperItemUtils.upperInfoName(order, prop);
        //排序字段
        String rowItem = UpperItemUtils.upperRowItem(prop);
        wpInfo.setRowItem(rowItem);
        if (StringUtils.isNotEmpty(wpInfo.getIsAccountable())){
            if ("0".equals(wpInfo.getIsAccountable())){
                wpInfo.setIsAccountable("不等于");
            }
            if ("1".equals(wpInfo.getIsAccountable())){
                wpInfo.setIsAccountable("等于");
            }

        }

        wpInfo.setOrderBy(orderBy);
        List<String> wpids = wpInfoMapper.getManageWpListAll(wpInfo);
        List<WpInfo> wpInfos = new ArrayList<>();
        if (wpids.size() == 0) {
            return getDataTable(wpInfos, wpids);
        }
        for (String wpid : wpids) {
            WpInfo wpInfoCon = wpInfoMapper.selectWpInfoByWpId(wpid);
            //话务员真实姓名
            if (StringUtils.isNotEmpty(wpInfoCon.getSender())) {
                SysUser sysUser = userMapper.selectUserByCode(wpInfoCon.getSender());
                if (sysUser != null) {
                    wpInfoCon.setInitiatorName(sysUser.getNickName());
                }

            }

            if (StringUtils.isNotEmpty(wpInfo.getIssatisfied())) {
                wpInfoCon.setIssatisfied(wpInfo.getIssatisfied());
            } else {
                WpVisitInfo wpVisitInfo = wpVisitInfoMapper.selectWpVisitInfoByWpid(wpid);
                if (wpVisitInfo != null) {
                    wpInfoCon.setIssatisfied(wpVisitInfo.getIssatisfied());
                }
            }
            if (StringUtils.isNotEmpty(wpInfoCon.getDeptLevel2())) {
                SysDept sysDept = sysDeptMapper.selectDeptById(Long.valueOf(wpInfoCon.getDeptLevel2()));
                if (sysDept != null) {
                    wpInfoCon.setMainUnitName(sysDept.getDeptName());
                }

            }
            String class1 = wpInfoCon.getClass1();
            String class2 = wpInfoCon.getClass2();
            String class3 = wpInfoCon.getClass3();
            String class4 = wpInfoCon.getClass4();

            StringBuffer name = new StringBuffer();

            if (StringUtils.isNotEmpty(class1)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class1));
                if (sysCode != null) {
                    wpInfoCon.setMainNodename(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(class2)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class2));
                if (sysCode != null) {
                    name.append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(class3)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class3));
                if (sysCode != null) {
                    name.append("/").append(sysCode.getNodename());
                }

            }
            if (StringUtils.isNotEmpty(class4)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class4));
                if (sysCode != null) {
                    name.append("/").append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(name)) {
                wpInfoCon.setChildNodeName(name.toString());
            }

            String cbdwComplete = wpInfoCon.getCbdwComplete();
            if (StringUtils.isNotEmpty(cbdwComplete)) {
                //已完成
                if (cbdwComplete.equals("1")) {
                    wpInfoCon.setResidue("已完成");
                } else if (cbdwComplete.equals("0")) {
                    // 老数据的处理方式--2025-09-10
                    if ("工单归档".equals(wpInfoCon.getNextState())) {
                        wpInfoCon.setResidue("已完成");
                    }else {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String timeBoundry = wpInfoCon.getTimeBoundry();
                        if (StringUtils.isNotEmpty(timeBoundry)) {
                            String residueDay = checkResidueDay(simpleDateFormat.parse(timeBoundry));
                            wpInfoCon.setResidue(residueDay);
                        }
                    }
                }
            }

            wpInfos.add(wpInfoCon);
        }
        return getDataTable(wpInfos, wpids);
    }

    @Override
    public List<WpInfo> reviewerReminderList(WpHurryLog wpHurryLog) {
        //排序相关
        String order = wpHurryLog.getOrder();
        String prop = wpHurryLog.getProp();
        String orderBy = UpperItemUtils.upperHurryInfoName(order, prop);
        String rowItem = UpperItemUtils.upperRowItem(prop);
        wpHurryLog.setRowItem(rowItem);

        wpHurryLog.setOrderBy(orderBy);

        List<WpInfo> wpInfoCons = wpHurryLogMapper.selectWpHurryLogWpidList(wpHurryLog);

        if (wpInfoCons.size() == 0) {
            return new ArrayList<WpInfo>();
        }

        List<String> wpids = wpInfoCons.stream().map(WpInfo::getWpid).collect(Collectors.toList());
        WpInfo infoCon = new WpInfo();
        infoCon.setWpids(wpids);

        String s = UpperItemUtils.upperName(order, prop);
        infoCon.setOrderBy(s);


        List<WpInfo> wpInfos = wpInfoMapper.selectWpInfoCountListByWpids(infoCon);
        for (WpInfo info : wpInfos) {

            String class1 = info.getClass1();
            String class2 = info.getClass2();
            String class3 = info.getClass3();
            String class4 = info.getClass4();

            StringBuffer name = new StringBuffer();

            if (StringUtils.isNotEmpty(class1)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class1));
                info.setMainNodename(sysCode.getNodename());
            }

            if (StringUtils.isNotEmpty(class2)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class2));
                name.append(sysCode.getNodename());
            }
            if (StringUtils.isNotEmpty(class3)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class3));
                name.append("/").append(sysCode.getNodename());
            }
            if (StringUtils.isNotEmpty(class4)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class4));
                name.append("/").append(sysCode.getNodename());
            }
            if (StringUtils.isNotEmpty(name)) {
                info.setChildNodeName(name.toString());
            }
        }

        return wpInfos;
    }

    @Override
    public Integer editRevokeWpInfo(String scid) {
        WpInfo wpInfo = wpInfoMapper.selectWpInfoByScid(scid);

        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (("督导处理".equals(wpInfo.getNextState()) || "培训助理处理".equals(wpInfo.getNextState()) || "质检审核处理".equals(wpInfo.getNextState()))
                && user.getCode().equals(wpInfo.getCode())) {

            //如果撤销，则将承办单位质控，办结状态置空
            if (("质检审核处理".equals(wpInfo.getNextState())||"督导处理".equals(wpInfo.getNextState()))){
                WpInfo infoCon = new WpInfo();
                infoCon.setDeptLevel2(null);
                infoCon.setMainUnit(null);
                infoCon.setAssistUnit1(null);
                infoCon.setDeptLevel2vice1(null);

                infoCon.setAssistUnit2(null);
                infoCon.setDeptLevel2vice2(null);
                infoCon.setScid(wpInfo.getScid());
                infoCon.setEndState(null);
                int i = wpInfoMapper.updateMainDeptByScid(infoCon);
            }

            WpInfo info = new WpInfo();
            info.setScid(scid);
            info.setUpdatetime(new Date());
            Integer integer = wpInfoMapper.editRevokeWpInfo(info);

            wpInfo.setState("坐席撤销工单");
            wpInfo.setNextState("坐席处理");
            wpInfo.setLastmessage("坐席撤销工单");
            this.insertWpHandleLog(wpInfo);
            return integer;
        } else {
            throw new BaseException("该工单不属于撤销流程，无法撤销！");
        }

    }

    @Override
    public void updateWpInfoSendSatis(String phoneno, Integer content) {
        log.info("更新短信满意度入参：手机号{},内容{}", phoneno, content);

        String scid = wpInfoMapper.findWpInfoByPhoneNew(phoneno);
        log.info("更新短信满意度工单主键id：{}", scid);
        if (scid != null) {
            WpInfo wpInfo = wpInfoMapper.selectWpInfoByScid(scid);
            if (wpInfo != null) {
                log.info("更新短信满意度工单编号：{}", wpInfo.getWpid());
                if (content == 1 || content == 2 || content == 3) {
                    wpInfo.setSendSatis(content);
                    wpInfoMapper.updateWpInfoSendSatis(wpInfo);
                }
            }

        }
    }

    @Override
    public WpInfo selectWpInfoByWpid(String wpid) {
        WpInfo wpInfo = wpInfoMapper.selectWpInfoByWpId(wpid);
        WpInfoCall wpInfoCall = new WpInfoCall();
        wpInfoCall.setWpid(wpid);

        ZjRecord zjRecord = new ZjRecord();
        zjRecord.setWpid(wpid);
        List<ZjRecord> zjRecords = zjRecordMapper.selectZjRecordListByWpid(zjRecord);
        /*if (zjRecord!=null){
            wpInfo.setRecordAddr(zjRecord.getRecordFilepath());
            wpInfo.setRecordCreateTime(zjRecord.getCreateTime());
        }*/
        ZjSoundCase zjSoundCase = zjSoundCaseMapper.selectZjSoundCaseByWpid(wpid);
        if (zjSoundCase != null) {
            wpInfo.setSubmitReason(zjSoundCase.getSubmitReason());
            wpInfo.setZjComment(zjSoundCase.getZjComment());
        }
        wpInfo.setRecordAddrs(zjRecords);
        return wpInfo;
    }

    @Override
    public List<WpInfo> selectWpBackInfoList(WpInfo wpInfo) throws ParseException {

        //排序相关
        String order = wpInfo.getOrder();
        String prop = wpInfo.getProp();
        if ("dictDataList".equals(prop)) {
            prop = "dictData";
        }
        if ("mainUnitName".equals(prop)) {
            prop = "mainUnit";
        }

        String orderBy = UpperItemUtils.upperName(order, prop);

        wpInfo.setOrderBy("info." + orderBy);
        List<WpInfo> wpInfos = wpInfoMapper.selectWpBackInfoList(wpInfo);
        for (WpInfo info : wpInfos) {
            String class1 = info.getClass1();
            String class2 = info.getClass2();
            String class3 = info.getClass3();
            String class4 = info.getClass4();

            StringBuffer name = new StringBuffer();

            if (StringUtils.isNotEmpty(class1)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class1));
                info.setMainNodename(sysCode.getNodename());
            }

            if (StringUtils.isNotEmpty(class2)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class2));
                name.append(sysCode.getNodename());
            }
            if (StringUtils.isNotEmpty(class3)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class3));
                name.append("/").append(sysCode.getNodename());
            }
            if (StringUtils.isNotEmpty(class4)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class4));
                name.append("/").append(sysCode.getNodename());
            }
            if (StringUtils.isNotEmpty(name)) {
                info.setChildNodeName(name.toString());
            }


            String cbdwComplete = info.getCbdwComplete();
            if (StringUtils.isNotEmpty(cbdwComplete)) {
                //已完成
                if (cbdwComplete.equals("1")) {
                    info.setResidue("已完成");
                } else if (cbdwComplete.equals("0")) {
                    // 老数据的处理方式--2025-09-10
                    if ("工单归档".equals(info.getNextState())) {
                        info.setResidue("已完成");
                    }else {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String timeBoundry = info.getTimeBoundry();
                        if (StringUtils.isNotEmpty(timeBoundry)) {
                            String residueDay = checkResidueDay(simpleDateFormat.parse(timeBoundry));
                            info.setResidue(residueDay);
                        }
                    }
                }
            }
        }
        return wpInfos;
    }

    @Override
    public void updateWpInfoByManagement(WpInfoManagementVO wpInfoManagementVO) {
        WpInfo info = new WpInfo();

        BeanUtils.copyProperties(wpInfoManagementVO, info);
        info.setRelDistrict(info.getDistrict());
        info.setRelCommittee(info.getCommittee());
        info.setRelStreet(info.getStreet());
        String join = StringUtils.join(info.getDictDataAll(), ",");
        info.setDictData(join);
        if (StringUtils.isEmpty(info.getNextState())) {
            info.setNextState(null);
        }
        wpInfoMapper.updateWpInfo(info);

    }

    @Override
    public List<WpInfo> getVistWpInfoList(WpInfo wpInfo) {

        // List<String> asList = Arrays.asList("工单暂存", "坐席处理", "坐席受理");
        List<String> districtAll = wpInfo.getDistrictAll();
        if (StringUtils.isNotEmpty(districtAll)) {
            for (int i = 0; i < districtAll.size(); i++) {
                if (i == 0) {
                    //区域
                    wpInfo.setDistrict(districtAll.get(i));
                }
                if (i == 1) {
                    //街道
                    wpInfo.setStreet(districtAll.get(i));
                }
                if (i == 2) {
                    //居委会
                    wpInfo.setCommittee(districtAll.get(i));

                }
            }
        }
        //内容分类查询条件
        List<List<String>> classAllFind = wpInfo.getClassAllFind();

        //内容分类查询
        if (StringUtils.isEmpty(classAllFind)) {
            wpInfo.setClassAll(null);
        } else {
            List<String> classAllCon = new ArrayList<>();
            for (List<String> strings : classAllFind) {
                classAllCon.add(strings.get(strings.size() - 1));
            }
            wpInfo.setClassAll(classAllCon);
        }
        //排序相关
        String order = wpInfo.getOrder();
        String prop = wpInfo.getProp();
        if ("dictDataList".equals(prop)) {
            prop = "dictData";
        }
        if ("initiatorName".equals(prop)) {
            prop = "sender";
        }
        if ("mainUnitName".equals(prop)) {
            prop = "mainUnit";
        }

        String orderBy = UpperItemUtils.upperName(order, prop);

        wpInfo.setOrderBy(orderBy);
        long l = System.currentTimeMillis();
        List<WpInfo> wpInfos = wpInfoMapper.getVistWpInfoList(wpInfo);

        log.info("查看待回访页面sql执行时长：{}", System.currentTimeMillis() - l);

        for (WpInfo info : wpInfos) {
            //查询轨迹表
            WpHandleLog wpHandleLog = new WpHandleLog();
            wpHandleLog.setWpid(info.getWpid());
            List<WpHandleLog> wpHandleLogs = wpHandleLogMapper.selectWpHandleLogList(wpHandleLog);
            wpHandleLogs.stream()
                    .filter(logCon -> "承办单位处理".equals(logCon.getLastState()))
                    .max(Comparator.comparing(WpHandleLog::getUpdateTime))
                    .ifPresent(log -> info.setAssistUnitMessage(log.getMessage()));

            //工单是否在处理中 true为处理中
            info.setProcessing(false);
            if (info.getCurrWorkTime() != null) {
                long currTime = System.currentTimeMillis();
                // 如果超过15分钟 当前处理人和时间
                long overTimeMin = (currTime - info.getCurrWorkTime()) / 1000L / 60L;
                boolean isOvertime = overTimeMin > EXPTIME;
                if (!isOvertime) {
                    info.setProcessing(true);
                }
            }
        }

        return wpInfos;

    }

    @Override
    public ResultMap orderListAppoint(Query queryMap) {
        List<WpInfoAppointDO> list = wpInfoMapper.orderListAppoint(queryMap);
        Integer total = wpInfoMapper.orderListAppointTotal(queryMap);
        com.community.common.utils.OldPageUtils pageUtils = new com.community.common.utils.OldPageUtils(list, total);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("pageUtil", pageUtils);
        return ResultMap.ok(resultMap);
    }

    @Override
    public ResultMap orderInfoAppoint(WpTraceBO wpTrace) {
        Map<String, Object> result = new HashMap<>();
        WpInfoAppointBO wpInfoAppointBO = new WpInfoAppointBO();
        List<WpHandleLogDO> wpHandleLogList = wpInfoMapper.orderTimeQuerySingle(wpTrace);
        wpHandleLogList.stream().forEach((item) -> {
            if ("工单回访".equals(item.getNextState())) {
                wpInfoAppointBO.setFinishDate(DateUtils.format(item.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"));
            } else {
                wpInfoAppointBO.setTransferDate(DateUtils.format(item.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"));
            }
        });
        List<WpVisitInfoDO> wpVisitInfoDOList = wpInfoMapper.orderSatisfiedQuerySingle(wpTrace);
        Optional<WpVisitInfoDO> wpVisitInfoOptional = wpVisitInfoDOList.stream().findFirst();
        if (wpVisitInfoOptional.isPresent()) {
            if (StringUtils.isEmpty((wpVisitInfoOptional.get()).getIsSatisfied())) {
                wpInfoAppointBO.setSatisfied("未评价");
            } else {
                wpInfoAppointBO.setSatisfied((wpVisitInfoOptional.get()).getIsSatisfied());
            }
        } else {
            wpInfoAppointBO.setSatisfied("未评价");
        }

        WpInfoBO wpInfoBO = wpInfoMapper.getOnlyWpInfo(wpTrace);
        wpInfoAppointBO.setSummary(wpInfoBO.getSummary());
        //处理描述
        wpInfoAppointBO.setLastMessage(wpInfoBO.getLastmessage());
        wpInfoAppointBO.setWpid(wpInfoBO.getWpid());
        wpInfoAppointBO.setCustomerName(wpInfoBO.getCustomerName());
        //地址
        wpInfoAppointBO.setRealAddress(wpInfoBO.getRelAddress());
        wpInfoAppointBO.setRealPhoneNo(wpInfoBO.getRelPhoneno());
        //答复要点
        wpInfoAppointBO.setReplyPoint(wpInfoBO.getReplyPoint());
        result.put("wpInfoAppoint", wpInfoAppointBO);
        return ResultMap.ok(result);
    }

    @Override
    public void updateSendSmsState(WpInfo info) {
        wpInfoMapper.updateSendSmsState(info);
    }

    @Transactional
    @Override
    public int updateVistSmsState(WpInfo info) {
        return wpInfoMapper.updateVistSmsState(info);
    }

    @Override
    public int addWpEvaluateSatis(WpEvaluateSatis wpEvaluateSatis) {
        WpEvaluateSatis evaluateSatis = wpEvaluateSatisMapper.getByWpid(wpEvaluateSatis.wpid);
        WpEvaluateSatis newWpEvaluateSatis = new WpEvaluateSatis();
        int i = 0;
        if (evaluateSatis == null) {
            newWpEvaluateSatis.setWpid(wpEvaluateSatis.wpid);
            newWpEvaluateSatis.setEvaluateSatis("1");
            newWpEvaluateSatis.setCreateTime(new Date());
            newWpEvaluateSatis.setUpdateTime(new Date());
            i = wpEvaluateSatisMapper.add(newWpEvaluateSatis);
        } else {
            newWpEvaluateSatis.setId(evaluateSatis.id);
            newWpEvaluateSatis.setUpdateTime(new Date());
            i = wpEvaluateSatisMapper.update(newWpEvaluateSatis);
        }
        return i;
    }

    @Override
    public Integer countTsWpid(WpInfo wpInfo) {
        return wpInfoMapper.countTsWpid(wpInfo);
    }

    @Override
    public void updateWpInfoSoundCase(WpInfo wpInfo) {
        wpInfoMapper.updateWpInfoSoundCase(wpInfo);
    }

    @Override
    public AjaxResult extensionWpinfoEdit(WpInfo wpInfo) {

        if ("1".equals(wpInfo.getExtensionStatus())) {
            wpInfo.setTimeBoundry(wpInfo.getExtensionTime());
        }

        return AjaxResult.success(wpInfoMapper.extensionWpinfoEdit(wpInfo));
    }

    @Override
    public List<WpInfo> getExtensionApplyList(WpInfo wpInfo) {
        //内容分类查询条件
        List<List<String>> classAllFind = wpInfo.getClassAllFind();

        //内容分类查询
        if (StringUtils.isEmpty(classAllFind)) {
            wpInfo.setClassAll(null);
        } else {
            List<String> classAllCon = new ArrayList<>();
            for (List<String> strings : classAllFind) {
                classAllCon.add(strings.get(strings.size() - 1));
            }
            wpInfo.setClassAll(classAllCon);
        }
        wpInfo.setNextState("承办单位处理");
        //延期申请状态
        wpInfo.setExtensionStatus("0");
        List<WpInfo> wpInfos = wpInfoMapper.selectWpInfoList(wpInfo);
        for (WpInfo info : wpInfos) {
            String extensionTime = info.getExtensionTime();
            String class1 = info.getClass1();
            String class2 = info.getClass2();
            String class3 = info.getClass3();
            String class4 = info.getClass4();

            StringBuffer name = new StringBuffer();

            if (StringUtils.isNotEmpty(class1)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class1));
                info.setMainNodename(sysCode.getNodename());
            }

            if (StringUtils.isNotEmpty(class2)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class2));
                name.append(sysCode.getNodename());
            }
            if (StringUtils.isNotEmpty(class3)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class3));
                name.append("/").append(sysCode.getNodename());
            }
            if (StringUtils.isNotEmpty(class4)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class4));
                name.append("/").append(sysCode.getNodename());
            }
            if (StringUtils.isNotEmpty(name)) {
                info.setChildNodeName(name.toString());
            }

        }
        return wpInfos;
    }

    @Override
    public List<WpInfo> organizerList(WpInfo wpInfo) {

        //内容分类查询条件
        List<List<String>> classAllFind = wpInfo.getClassAllFind();

        //内容分类查询
        if (StringUtils.isEmpty(classAllFind)) {
            wpInfo.setClassAll(null);
        } else {
            List<String> classAllCon = new ArrayList<>();
            for (List<String> strings : classAllFind) {
                classAllCon.add(strings.get(strings.size() - 1));
            }
            wpInfo.setClassAll(classAllCon);
        }
        //排序相关
        String order = wpInfo.getOrder();
        String prop = wpInfo.getProp();
        if ("dictDataList".equals(prop)) {
            prop = "dictData";
        }
        if ("initiatorName".equals(prop)) {
            prop = "sender";
        }
        if ("mainUnitName".equals(prop)) {
            prop = "mainUnit";
        }

        String orderBy = UpperItemUtils.upperName(order, prop);
        wpInfo.setOrderBy(orderBy);

        List<WpInfo> wpInfos = wpInfoMapper.organizerList(wpInfo);
        Set<String> codeSet = new HashSet<>(wpInfos.size() + 6);
        wpInfos.stream().forEach(w -> {
            if (StringUtils.isNotEmpty(w.getCode())) {
                codeSet.add(w.getCode());
            }
        });
        List<SysUser> codeUsetList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(codeSet)) {
            List<String> codeList = new ArrayList<>();
            codeList.addAll(codeSet);
            codeUsetList = userMapper.getUserByCodes(codeList);
        }
        for (WpInfo info : wpInfos) {
            WpHandleLog wpHandleLog = new WpHandleLog();
            wpHandleLog.setWpid(info.getWpid());
            wpHandleLogMapper.selectWpHandleLogList(wpHandleLog)
                    .stream()
                    .filter(handlog -> "承办单位处理".equals(handlog.getNextState()))
                    .max(Comparator.comparing(WpHandleLog::getUpdateTime))
                    .ifPresent(anElse -> info.setCalltime(anElse.getUpdateTime()));
            if (!StringUtils.isEmpty(info.getPhoneno())) {
                String phoneno = info.getPhoneno();
                Integer countSize = wpInfoMapper.countWpInfoByPhoneno(phoneno);
                info.setPhoneCalls(countSize);
            }
            if (StringUtils.isNotEmpty(info.getDeptLevel2())) {
                SysDept sysDept = sysDeptMapper.selectDeptById(Long.valueOf(info.getDeptLevel2()));
                if (sysDept != null) {
                    info.setMainUnitName(sysDept.getDeptName());
                }

            }
            //工单是否在处理中 true为处理中
            info.setProcessing(false);
            if (info.getCurrWorkTime() != null) {
                long currTime = System.currentTimeMillis();
                // 如果超过15分钟 当前处理人和时间
                long overTimeMin = (currTime - info.getCurrWorkTime()) / 1000L / 60L;
                boolean isOvertime = overTimeMin > EXPTIME;
                if (!isOvertime) {
                    info.setProcessing(true);
                }

            }
            String class1 = info.getClass1();
            String class2 = info.getClass2();
            String class3 = info.getClass3();
            String class4 = info.getClass4();

            StringBuffer name = new StringBuffer();

            if (StringUtils.isNotEmpty(class1)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class1));
                if (sysCode != null) {
                    info.setMainNodename(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(class2)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class2));
                if (sysCode != null) {
                    name.append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(class3)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class3));
                if (sysCode != null) {
                    name.append("/").append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(class4)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class4));
                if (sysCode != null) {
                    name.append("/").append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(name)) {
                info.setChildNodeName(name.toString());
            }


            String cbdwComplete = info.getCbdwComplete();
            if (StringUtils.isNotEmpty(cbdwComplete)) {
                //已完成
                if (cbdwComplete.equals("1")) {
                    info.setResidue("已完成");
                } else if (cbdwComplete.equals("0")) {
                    // 老数据的处理方式--2025-09-10
                    if ("工单归档".equals(info.getNextState())) {
                        info.setResidue("已完成");
                    }else {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String timeBoundry = info.getTimeBoundry();
                        if (StringUtils.isNotEmpty(timeBoundry)) {
                            try {
                                String residueDay = checkResidueDay(simpleDateFormat.parse(timeBoundry));
                                info.setResidue(residueDay);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }

            // 根据工号查询用户姓名
            if (StringUtils.isNotEmpty(info.getCode())) {
                if (!CollectionUtils.isEmpty(codeUsetList)) {
                    for (SysUser codeUser : codeUsetList) {
                        if (info.getCode().equals(codeUser.getCode())) {
                            info.setInitiatorName(codeUser.getNickName());
                            break;
                        }
                    }
                }
            }

        }

        return wpInfos;
    }

    @Override
    public WpInfo selectWpInfoByWpidFindDetail(String wpid) {

        WpInfo wpInfo = wpInfoMapper.selectWpInfoByWpId(wpid);
        if (wpInfo == null) {
            throw new BaseException("未查询到工单");
        }
        ZjSoundCase zjSoundCase = zjSoundCaseMapper.selectZjSoundCaseByWpid(wpInfo.getWpid());
        if (zjSoundCase != null) {
            wpInfo.setSubmitReason(zjSoundCase.getSubmitReason());
        }
        if (StringUtils.isNotEmpty(wpInfo.getCause())) {
            String cause = wpInfo.getCause();
            List<String> causeList = new ArrayList<>(Arrays.asList(cause.split(",")));
            wpInfo.setCauseList(causeList);
        }
        //工单标签
        if (StringUtils.isNotEmpty(wpInfo.getDictData())) {
            String[] split = wpInfo.getDictData().split(",");
            Long[] longs = new Long[split.length];

            for (int i = 0; i < split.length; i++) {
                longs[i] = Long.parseLong(split[i]);
            }
            List<Long> dictDataAll = new ArrayList<>();
            Collections.addAll(dictDataAll, longs);
            wpInfo.setDictDataAll(dictDataAll);
        }
        String fileno = wpInfo.getFileno();
        if (fileno != null) {
            String[] split = wpInfo.getFileno().split(",");
            if (split.length > 0) {
                List<SysMiniFile> sysMiniFiles = sysMiniFileMapper.selectSysMiniFileByIds(split);
                wpInfo.setSysMiniFiles(sysMiniFiles);
            }
        }
        WpHandleLog wpHandleLog = new WpHandleLog();
        wpHandleLog.setWpid(wpInfo.getWpid());
        List<WpHandleLog> wpHandleLogs = wpHandleLogMapper.selectWpHandleLogList(wpHandleLog);
        if (!wpHandleLogs.isEmpty()) {

            //只有承办单位处理的时候会多出这几个字段
            WpHandleLog logCon = wpHandleLogs.stream()
                    .filter(log -> "承办单位处理".equals(log.getLastState()))
                    .max(Comparator.comparing(WpHandleLog::getUpdateTime)).orElse(null);
            if (logCon != null) {
                //工单轨迹特有字段
                wpInfo.setSatisfied(logCon.getSatisfied());
                wpInfo.setReasonable(logCon.getReasonable());
                wpInfo.setSolved(logCon.getSolved());
            }

            //退单展示退单原因   督导退回坐席
            WpHandleLog logCon1 = wpHandleLogs.stream()
                    .filter(logHan -> "坐席处理".equals(logHan.getNextState()) &&
                            ("督导处理".equals(logHan.getLastState())
                                    || "培训助理处理".equals(logHan.getLastState())
                                    || "质检审核处理".equals(logHan.getLastState())))
                    .max(Comparator.comparing(WpHandleLog::getUpdateTime)).orElse(null);
            if (logCon1 != null) {
                wpInfo.setBackClass(logCon1.getBackClass());
            }
            // 循环查询工单轨迹
            for (WpHandleLog handleLog : wpHandleLogs) {
                if (StringUtils.isNotEmpty(handleLog.getOperator())) {
                    SysUser user = userMapper.selectUserByCode(handleLog.getOperator());
                    if (user != null) {
                        handleLog.setNickName(user.getNickName());
                    }
                }
                if (StringUtils.isNotEmpty(handleLog.getDepartment())) {
                    SysDept sysDept = sysDeptMapper.selectDeptById(Long.valueOf(handleLog.getDepartment()));
                    if (sysDept != null) {
                        handleLog.setDepartmentName(sysDept.getDeptName());
                    }
                }
            }
            wpInfo.setWpHandleLogs(wpHandleLogs);
        }
        //处理工单回访过的工单，需要展示回访满意度字段
        if ("工单回访".equals(wpInfo.getState())) {
            WpVisitInfo wpVisitInfo = wpVisitInfoMapper.selectWpVisitInfoByWpid(wpInfo.getWpid());
            if (wpVisitInfo != null) {
                wpInfo.setAcceptVisit(wpVisitInfo.getAcceptVisit());
                wpInfo.setIsanswer(wpVisitInfo.getIsanswer());
                wpInfo.setIssatisfied(wpVisitInfo.getIssatisfied());
                wpInfo.setIsReply(wpVisitInfo.getIsReply());
                wpInfo.setIssatisfiedReason(wpVisitInfo.getIssatisfiedReason());
                wpInfo.setIssatisfiedOther(wpVisitInfo.getIssatisfiedOther());
            }
        }

        return wpInfo;
    }

    @Override
    public int updateWpInfoSatis(WpInfo wpInfo) {
        return wpInfoMapper.updateWpInfoSatis(wpInfo);
    }

    @Override
    public TableDataInfo selectManageWpListAll(WpInfo wpInfo) throws ParseException {
        List<String> wpids = wpInfoMapper.selectManageWpListAll(wpInfo);
        List<WpInfo> wpInfos = new ArrayList<>();
        if (wpids.size() == 0) {
            return getDataTable(wpInfos, wpids);
        }
        for (String wpid : wpids) {
            WpInfo wpInfoCon = wpInfoMapper.selectWpInfoByWpId(wpid);
            //话务员真实姓名
            if (StringUtils.isNotEmpty(wpInfoCon.getSender())) {
                SysUser sysUser = userMapper.selectUserByCode(wpInfoCon.getSender());
                if (sysUser != null) {
                    wpInfoCon.setInitiatorName(sysUser.getNickName());
                }

            }

            if (StringUtils.isNotEmpty(wpInfo.getIssatisfied())) {
                wpInfoCon.setIssatisfied(wpInfo.getIssatisfied());
            } else {
                WpVisitInfo wpVisitInfo = wpVisitInfoMapper.selectWpVisitInfoByWpid(wpid);
                if (wpVisitInfo != null) {
                    wpInfoCon.setIssatisfied(wpVisitInfo.getIssatisfied());
                }
            }
            if (StringUtils.isNotEmpty(wpInfoCon.getDeptLevel2())) {
                SysDept sysDept = sysDeptMapper.selectDeptById(Long.valueOf(wpInfoCon.getDeptLevel2()));
                if (sysDept != null) {
                    wpInfoCon.setMainUnitName(sysDept.getDeptName());
                }

            }
            String class1 = wpInfoCon.getClass1();
            String class2 = wpInfoCon.getClass2();
            String class3 = wpInfoCon.getClass3();
            String class4 = wpInfoCon.getClass4();

            StringBuffer name = new StringBuffer();

            if (StringUtils.isNotEmpty(class1)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class1));
                if (sysCode != null) {
                    wpInfoCon.setMainNodename(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(class2)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class2));
                if (sysCode != null) {
                    name.append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(class3)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class3));
                if (sysCode != null) {
                    name.append("/").append(sysCode.getNodename());
                }

            }
            if (StringUtils.isNotEmpty(class4)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class4));
                if (sysCode != null) {
                    name.append("/").append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(name)) {
                wpInfoCon.setChildNodeName(name.toString());
            }

            String cbdwComplete = wpInfoCon.getCbdwComplete();
            if (StringUtils.isNotEmpty(cbdwComplete)) {
                //已完成
                if (cbdwComplete.equals("1")) {
                    wpInfoCon.setResidue("已完成");
                } else if (cbdwComplete.equals("0")) {
                    // 老数据的处理方式--2025-09-10
                    if ("工单归档".equals(wpInfoCon.getNextState())) {
                        wpInfoCon.setResidue("已完成");
                    }else {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String timeBoundry = wpInfoCon.getTimeBoundry();
                        if (StringUtils.isNotEmpty(timeBoundry)) {
                            String residueDay = checkResidueDay(simpleDateFormat.parse(timeBoundry));
                            wpInfoCon.setResidue(residueDay);
                        }
                    }
                }
            }

            wpInfos.add(wpInfoCon);
        }
        return getDataTable(wpInfos, wpids);
    }


    public String generateWpId(String channel) {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String date = formatter.format(System.currentTimeMillis());
        long incr;
        if (redisService.exists(date)) {
            incr = redisService.incr(date, EXPIRE);
        } else {
            incr = redisService.incr(date, EXPIRE);
        }
        String orderNumber = automaticFilling((int) incr, 5);
        String workOrderNumber = channel + date + orderNumber;

        return workOrderNumber;
    }

    /**
     * 自动补位
     *
     * @param code 数值
     * @param num  保留的位数
     * @return
     */
    public static String automaticFilling(int code, int num) {
        return String.format("%0" + num + "d", code);
    }

    /**
     * 根据天数去除节假日返回对应日期
     *
     * @param date
     * @param day
     * @return
     */
    public Date checkOntime(Date date, Integer day) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        long year = calendar.get(Calendar.YEAR);
        WpHoliday wpHoliday = new WpHoliday();
        wpHoliday.setYearid(year);
        List<WpHoliday> wpHolidays = wpHolidayMapper.selectWpHolidayList(wpHoliday);

        List<String> dates = wpHolidays.stream()
                .map(WpHoliday::getDtime)
                .map(simpleDateFormat::format)
                .collect(Collectors.toList());
        String lasetDate = "";
        for (int i = 1; i <= day; i++) {
            lasetDate = addDay(date, i);
            if (dates.contains(lasetDate)) {
                day++;
            }
        }
        Date parseCon = null;
        try {
            Date parse = simpleDateFormat.parse(lasetDate);
            String format = DateFormatUtils.format(parse, "yyyy-MM-dd 23:59:59");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            parseCon = dateFormat.parse(format);
        } catch (ParseException e) {
            throw new BaseException("日期转换错误！");
        }
        return parseCon;

    }


    /**
     * @param date 日期
     * @return 加算后的日期
     * @Description 参数的日期加指定的日
     */
    public static String addDay(Date date, int day) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, day);

        return simpleDateFormat.format(calendar.getTime());
    }

    /**
     * 检测剩余天数
     *
     * @return
     */
    public String checkResidueDay(Date date) throws ParseException {

        int day = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        long year = calendar.get(Calendar.YEAR);
        WpHoliday wpHoliday = new WpHoliday();
        wpHoliday.setYearid(year);
        List<WpHoliday> wpHolidays = wpHolidayMapper.selectWpHolidayList(wpHoliday);

        List<String> dates = wpHolidays.stream()
                .map(WpHoliday::getDtime)
                .map(simpleDateFormat::format)
                .collect(Collectors.toList());
        Date dateNew = new Date();
        String format = simpleDateFormat.format(dateNew);
        Date parse = simpleDateFormat.parse(format);
        String lasetDate = "";

        if (parse.compareTo(date) <= 0) {

            long now = date.getTime();
            long old = parse.getTime();
            long betweenDays = (now - old) / 24 / 60 / 60 / 1000;
            if (betweenDays == 0) {

            }
            for (int i = 0; i < betweenDays; i++) {
                lasetDate = addDay(parse, i);
                if (!dates.contains(lasetDate)) {
                    day++;
                }
            }
            return "剩余" + day + "天";
        } else {
            long now = date.getTime();
            long old = parse.getTime();
            long betweenDays = (old - now) / 24 / 60 / 60 / 1000;
            for (int i = 0; i <= betweenDays; i++) {
                lasetDate = addDay(date, i);
                if (!dates.contains(lasetDate)) {
                    day++;
                }
            }
            return "超时" + day + "天";

        }

    }

    protected TableDataInfo getDataTable(List<?> list, List<?> total) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(total).getTotal());
        return rspData;
    }


}
